blob: b959202b88562d05cab228afd963d9ce8cb9693d [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);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000589 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
590 if (!Class)
591 return true;
592
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000593 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
595 Virtual, Access,
596 BaseType, BaseLoc))
597 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000600}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000601
Douglas Gregor2943aed2009-03-03 04:44:36 +0000602/// \brief Performs the actual work of attaching the given base class
603/// specifiers to a C++ class.
604bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
605 unsigned NumBases) {
606 if (NumBases == 0)
607 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000608
609 // Used to keep track of which base types we have already seen, so
610 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000611 // that the key is always the unqualified canonical type of the base
612 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000613 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
614
615 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000616 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000618 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000619 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000621 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000622
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000623 if (KnownBaseTypes[NewBaseType]) {
624 // C++ [class.mi]p3:
625 // A class shall not be specified as a direct base class of a
626 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000628 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000629 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000630 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000631
632 // Delete the duplicate base class specifier; we're going to
633 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000634 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635
636 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000637 } else {
638 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 KnownBaseTypes[NewBaseType] = Bases[idx];
640 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000641 }
642 }
643
644 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000645 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000646
647 // Delete the remaining (good) base class specifiers, since their
648 // data has been copied into the CXXRecordDecl.
649 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000650 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000651
652 return Invalid;
653}
654
655/// ActOnBaseSpecifiers - Attach the given base specifiers to the
656/// class, after checking whether there are any duplicate base
657/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000658void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659 unsigned NumBases) {
660 if (!ClassDecl || !Bases || !NumBases)
661 return;
662
663 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000664 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000665 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000666}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000667
Douglas Gregora8f32e02009-10-06 17:59:45 +0000668/// \brief Determine whether the type \p Derived is a C++ class that is
669/// derived from the type \p Base.
670bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
671 if (!getLangOptions().CPlusPlus)
672 return false;
673
674 const RecordType *DerivedRT = Derived->getAs<RecordType>();
675 if (!DerivedRT)
676 return false;
677
678 const RecordType *BaseRT = Base->getAs<RecordType>();
679 if (!BaseRT)
680 return false;
681
682 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
683 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall86ff3082010-02-04 22:26:26 +0000684 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
685 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686}
687
688/// \brief Determine whether the type \p Derived is a C++ class that is
689/// derived from the type \p Base.
690bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
691 if (!getLangOptions().CPlusPlus)
692 return false;
693
694 const RecordType *DerivedRT = Derived->getAs<RecordType>();
695 if (!DerivedRT)
696 return false;
697
698 const RecordType *BaseRT = Base->getAs<RecordType>();
699 if (!BaseRT)
700 return false;
701
702 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
703 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
704 return DerivedRD->isDerivedFrom(BaseRD, Paths);
705}
706
707/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
708/// conversion (where Derived and Base are class types) is
709/// well-formed, meaning that the conversion is unambiguous (and
710/// that all of the base classes are accessible). Returns true
711/// and emits a diagnostic if the code is ill-formed, returns false
712/// otherwise. Loc is the location where this routine should point to
713/// if there is an error, and Range is the source range to highlight
714/// if there is an error.
715bool
716Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000717 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000718 unsigned AmbigiousBaseConvID,
719 SourceLocation Loc, SourceRange Range,
720 DeclarationName Name) {
721 // First, determine whether the path from Derived to Base is
722 // ambiguous. This is slightly more expensive than checking whether
723 // the Derived to Base conversion exists, because here we need to
724 // explore multiple paths to determine if there is an ambiguity.
725 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
726 /*DetectVirtual=*/false);
727 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
728 assert(DerivationOkay &&
729 "Can only be used with a derived-to-base conversion");
730 (void)DerivationOkay;
731
732 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000733 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000734 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000735
Douglas Gregora8f32e02009-10-06 17:59:45 +0000736 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000737 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
738 Base, Derived, Paths.front(),
739 /*force*/ false,
740 /*unprivileged*/ false,
741 ADK)) {
742 case AR_accessible: return false;
743 case AR_inaccessible: return true;
744 case AR_dependent: return false;
745 case AR_delayed: return false;
746 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 }
748
749 // We know that the derived-to-base conversion is ambiguous, and
750 // we're going to produce a diagnostic. Perform the derived-to-base
751 // search just one more time to compute all of the possible paths so
752 // that we can print them out. This is more expensive than any of
753 // the previous derived-to-base checks we've done, but at this point
754 // performance isn't as much of an issue.
755 Paths.clear();
756 Paths.setRecordingPaths(true);
757 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
758 assert(StillOkay && "Can only be used with a derived-to-base conversion");
759 (void)StillOkay;
760
761 // Build up a textual representation of the ambiguous paths, e.g.,
762 // D -> B -> A, that will be used to illustrate the ambiguous
763 // conversions in the diagnostic. We only print one of the paths
764 // to each base class subobject.
765 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
766
767 Diag(Loc, AmbigiousBaseConvID)
768 << Derived << Base << PathDisplayStr << Range << Name;
769 return true;
770}
771
772bool
773Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000774 SourceLocation Loc, SourceRange Range,
775 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000776 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000777 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000778 diag::err_ambiguous_derived_to_base_conv,
779 Loc, Range, DeclarationName());
780}
781
782
783/// @brief Builds a string representing ambiguous paths from a
784/// specific derived class to different subobjects of the same base
785/// class.
786///
787/// This function builds a string that can be used in error messages
788/// to show the different paths that one can take through the
789/// inheritance hierarchy to go from the derived class to different
790/// subobjects of a base class. The result looks something like this:
791/// @code
792/// struct D -> struct B -> struct A
793/// struct D -> struct C -> struct A
794/// @endcode
795std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
796 std::string PathDisplayStr;
797 std::set<unsigned> DisplayedPaths;
798 for (CXXBasePaths::paths_iterator Path = Paths.begin();
799 Path != Paths.end(); ++Path) {
800 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
801 // We haven't displayed a path to this particular base
802 // class subobject yet.
803 PathDisplayStr += "\n ";
804 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
805 for (CXXBasePath::const_iterator Element = Path->begin();
806 Element != Path->end(); ++Element)
807 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
808 }
809 }
810
811 return PathDisplayStr;
812}
813
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000814//===----------------------------------------------------------------------===//
815// C++ class member Handling
816//===----------------------------------------------------------------------===//
817
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000818/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
819/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
820/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000821/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000822Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000823Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000824 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000825 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
826 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000827 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000828 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829 Expr *BitWidth = static_cast<Expr*>(BW);
830 Expr *Init = static_cast<Expr*>(InitExpr);
831 SourceLocation Loc = D.getIdentifierLoc();
832
Sebastian Redl669d5d72008-11-14 23:42:31 +0000833 bool isFunc = D.isFunctionDeclarator();
834
John McCall67d1a672009-08-06 02:15:43 +0000835 assert(!DS.isFriendSpecified());
836
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000837 // C++ 9.2p6: A member shall not be declared to have automatic storage
838 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000839 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
840 // data members and cannot be applied to names declared const or static,
841 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 switch (DS.getStorageClassSpec()) {
843 case DeclSpec::SCS_unspecified:
844 case DeclSpec::SCS_typedef:
845 case DeclSpec::SCS_static:
846 // FALL THROUGH.
847 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000848 case DeclSpec::SCS_mutable:
849 if (isFunc) {
850 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000851 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000852 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000853 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Sebastian Redla11f42f2008-11-17 23:24:37 +0000855 // FIXME: It would be nicer if the keyword was ignored only for this
856 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000857 D.getMutableDeclSpec().ClearStorageClassSpecs();
858 } else {
859 QualType T = GetTypeForDeclarator(D, S);
860 diag::kind err = static_cast<diag::kind>(0);
861 if (T->isReferenceType())
862 err = diag::err_mutable_reference;
863 else if (T.isConstQualified())
864 err = diag::err_mutable_const;
865 if (err != 0) {
866 if (DS.getStorageClassSpecLoc().isValid())
867 Diag(DS.getStorageClassSpecLoc(), err);
868 else
869 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000870 // FIXME: It would be nicer if the keyword was ignored only for this
871 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000872 D.getMutableDeclSpec().ClearStorageClassSpecs();
873 }
874 }
875 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000876 default:
877 if (DS.getStorageClassSpecLoc().isValid())
878 Diag(DS.getStorageClassSpecLoc(),
879 diag::err_storageclass_invalid_for_member);
880 else
881 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
882 D.getMutableDeclSpec().ClearStorageClassSpecs();
883 }
884
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000885 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000886 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000887 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000888 // Check also for this case:
889 //
890 // typedef int f();
891 // f a;
892 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000893 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000894 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000895 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000896
Sebastian Redl669d5d72008-11-14 23:42:31 +0000897 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
898 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000899 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000900
901 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000902 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000903 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000904 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
905 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000906 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000907 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000908 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000909 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000910 if (!Member) {
911 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000912 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000913 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000914
915 // Non-instance-fields can't have a bitfield.
916 if (BitWidth) {
917 if (Member->isInvalidDecl()) {
918 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000919 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000920 // C++ 9.6p3: A bit-field shall not be a static member.
921 // "static member 'A' cannot be a bit-field"
922 Diag(Loc, diag::err_static_not_bitfield)
923 << Name << BitWidth->getSourceRange();
924 } else if (isa<TypedefDecl>(Member)) {
925 // "typedef member 'x' cannot be a bit-field"
926 Diag(Loc, diag::err_typedef_not_bitfield)
927 << Name << BitWidth->getSourceRange();
928 } else {
929 // A function typedef ("typedef int f(); f a;").
930 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
931 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000932 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000933 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner8b963ef2009-03-05 23:01:03 +0000936 DeleteExpr(BitWidth);
937 BitWidth = 0;
938 Member->setInvalidDecl();
939 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000940
941 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregor37b372b2009-08-20 22:52:58 +0000943 // If we have declared a member function template, set the access of the
944 // templated declaration as well.
945 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
946 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000947 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000948
Douglas Gregor10bd3682008-11-17 22:58:34 +0000949 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000950
Douglas Gregor021c3b32009-03-11 23:00:04 +0000951 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000952 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000953 if (Deleted) // FIXME: Source location is not very good.
954 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000955
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000956 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000957 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000958 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000959 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000960 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000961}
962
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000963/// \brief Find the direct and/or virtual base specifiers that
964/// correspond to the given base type, for use in base initialization
965/// within a constructor.
966static bool FindBaseInitializer(Sema &SemaRef,
967 CXXRecordDecl *ClassDecl,
968 QualType BaseType,
969 const CXXBaseSpecifier *&DirectBaseSpec,
970 const CXXBaseSpecifier *&VirtualBaseSpec) {
971 // First, check for a direct base class.
972 DirectBaseSpec = 0;
973 for (CXXRecordDecl::base_class_const_iterator Base
974 = ClassDecl->bases_begin();
975 Base != ClassDecl->bases_end(); ++Base) {
976 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
977 // We found a direct base of this type. That's what we're
978 // initializing.
979 DirectBaseSpec = &*Base;
980 break;
981 }
982 }
983
984 // Check for a virtual base class.
985 // FIXME: We might be able to short-circuit this if we know in advance that
986 // there are no virtual bases.
987 VirtualBaseSpec = 0;
988 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
989 // We haven't found a base yet; search the class hierarchy for a
990 // virtual base class.
991 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
992 /*DetectVirtual=*/false);
993 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
994 BaseType, Paths)) {
995 for (CXXBasePaths::paths_iterator Path = Paths.begin();
996 Path != Paths.end(); ++Path) {
997 if (Path->back().Base->isVirtual()) {
998 VirtualBaseSpec = Path->back().Base;
999 break;
1000 }
1001 }
1002 }
1003 }
1004
1005 return DirectBaseSpec || VirtualBaseSpec;
1006}
1007
Douglas Gregor7ad83902008-11-05 04:29:56 +00001008/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001009Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001010Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001011 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001012 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001013 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001014 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001015 SourceLocation IdLoc,
1016 SourceLocation LParenLoc,
1017 ExprTy **Args, unsigned NumArgs,
1018 SourceLocation *CommaLocs,
1019 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001020 if (!ConstructorD)
1021 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001023 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
1025 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001026 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001027 if (!Constructor) {
1028 // The user wrote a constructor initializer on a function that is
1029 // not a C++ constructor. Ignore the error for now, because we may
1030 // have more member initializers coming; we'll diagnose it just
1031 // once in ActOnMemInitializers.
1032 return true;
1033 }
1034
1035 CXXRecordDecl *ClassDecl = Constructor->getParent();
1036
1037 // C++ [class.base.init]p2:
1038 // Names in a mem-initializer-id are looked up in the scope of the
1039 // constructor’s class and, if not found in that scope, are looked
1040 // up in the scope containing the constructor’s
1041 // definition. [Note: if the constructor’s class contains a member
1042 // with the same name as a direct or virtual base class of the
1043 // class, a mem-initializer-id naming the member or base class and
1044 // composed of a single identifier refers to the class member. A
1045 // mem-initializer-id for the hidden base class may be specified
1046 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001047 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001048 // Look for a member, first.
1049 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001050 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001051 = ClassDecl->lookup(MemberOrBase);
1052 if (Result.first != Result.second)
1053 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001054
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001055 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001056
Eli Friedman59c04372009-07-29 19:44:27 +00001057 if (Member)
1058 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001059 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001060 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001062 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001063 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001064
1065 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001066 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001067 } else {
1068 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1069 LookupParsedName(R, S, &SS);
1070
1071 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1072 if (!TyD) {
1073 if (R.isAmbiguous()) return true;
1074
Douglas Gregor7a886e12010-01-19 06:46:48 +00001075 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1076 bool NotUnknownSpecialization = false;
1077 DeclContext *DC = computeDeclContext(SS, false);
1078 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1079 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1080
1081 if (!NotUnknownSpecialization) {
1082 // When the scope specifier can refer to a member of an unknown
1083 // specialization, we take it as a type name.
1084 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1085 *MemberOrBase, SS.getRange());
1086 R.clear();
1087 }
1088 }
1089
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001090 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001091 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001092 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1093 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1094 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1095 // We have found a non-static data member with a similar
1096 // name to what was typed; complain and initialize that
1097 // member.
1098 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1099 << MemberOrBase << true << R.getLookupName()
1100 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1101 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001102 Diag(Member->getLocation(), diag::note_previous_decl)
1103 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001104
1105 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1106 LParenLoc, RParenLoc);
1107 }
1108 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1109 const CXXBaseSpecifier *DirectBaseSpec;
1110 const CXXBaseSpecifier *VirtualBaseSpec;
1111 if (FindBaseInitializer(*this, ClassDecl,
1112 Context.getTypeDeclType(Type),
1113 DirectBaseSpec, VirtualBaseSpec)) {
1114 // We have found a direct or virtual base class with a
1115 // similar name to what was typed; complain and initialize
1116 // that base class.
1117 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1118 << MemberOrBase << false << R.getLookupName()
1119 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1120 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001121
1122 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1123 : VirtualBaseSpec;
1124 Diag(BaseSpec->getSourceRange().getBegin(),
1125 diag::note_base_class_specified_here)
1126 << BaseSpec->getType()
1127 << BaseSpec->getSourceRange();
1128
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001129 TyD = Type;
1130 }
1131 }
1132 }
1133
Douglas Gregor7a886e12010-01-19 06:46:48 +00001134 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001135 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1136 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1137 return true;
1138 }
John McCall2b194412009-12-21 10:41:20 +00001139 }
1140
Douglas Gregor7a886e12010-01-19 06:46:48 +00001141 if (BaseType.isNull()) {
1142 BaseType = Context.getTypeDeclType(TyD);
1143 if (SS.isSet()) {
1144 NestedNameSpecifier *Qualifier =
1145 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001146
Douglas Gregor7a886e12010-01-19 06:46:48 +00001147 // FIXME: preserve source range information
1148 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1149 }
John McCall2b194412009-12-21 10:41:20 +00001150 }
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
John McCalla93c9342009-12-07 02:54:59 +00001153 if (!TInfo)
1154 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001155
John McCalla93c9342009-12-07 02:54:59 +00001156 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001157 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001158}
1159
John McCallb4190042009-11-04 23:02:40 +00001160/// Checks an initializer expression for use of uninitialized fields, such as
1161/// containing the field that is being initialized. Returns true if there is an
1162/// uninitialized field was used an updates the SourceLocation parameter; false
1163/// otherwise.
1164static bool InitExprContainsUninitializedFields(const Stmt* S,
1165 const FieldDecl* LhsField,
1166 SourceLocation* L) {
1167 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1168 if (ME) {
1169 const NamedDecl* RhsField = ME->getMemberDecl();
1170 if (RhsField == LhsField) {
1171 // Initializing a field with itself. Throw a warning.
1172 // But wait; there are exceptions!
1173 // Exception #1: The field may not belong to this record.
1174 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1175 const Expr* base = ME->getBase();
1176 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1177 // Even though the field matches, it does not belong to this record.
1178 return false;
1179 }
1180 // None of the exceptions triggered; return true to indicate an
1181 // uninitialized field was used.
1182 *L = ME->getMemberLoc();
1183 return true;
1184 }
1185 }
1186 bool found = false;
1187 for (Stmt::const_child_iterator it = S->child_begin();
1188 it != S->child_end() && found == false;
1189 ++it) {
1190 if (isa<CallExpr>(S)) {
1191 // Do not descend into function calls or constructors, as the use
1192 // of an uninitialized field may be valid. One would have to inspect
1193 // the contents of the function/ctor to determine if it is safe or not.
1194 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1195 // may be safe, depending on what the function/ctor does.
1196 continue;
1197 }
1198 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1199 }
1200 return found;
1201}
1202
Eli Friedman59c04372009-07-29 19:44:27 +00001203Sema::MemInitResult
1204Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1205 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001206 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001207 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001208 // Diagnose value-uses of fields to initialize themselves, e.g.
1209 // foo(foo)
1210 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001211 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001212 for (unsigned i = 0; i < NumArgs; ++i) {
1213 SourceLocation L;
1214 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1215 // FIXME: Return true in the case when other fields are used before being
1216 // uninitialized. For example, let this field be the i'th field. When
1217 // initializing the i'th field, throw a warning if any of the >= i'th
1218 // fields are used, as they are not yet initialized.
1219 // Right now we are only handling the case where the i'th field uses
1220 // itself in its initializer.
1221 Diag(L, diag::warn_field_is_uninit);
1222 }
1223 }
1224
Eli Friedman59c04372009-07-29 19:44:27 +00001225 bool HasDependentArg = false;
1226 for (unsigned i = 0; i < NumArgs; i++)
1227 HasDependentArg |= Args[i]->isTypeDependent();
1228
Eli Friedman59c04372009-07-29 19:44:27 +00001229 QualType FieldType = Member->getType();
1230 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1231 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001232 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001233 if (FieldType->isDependentType() || HasDependentArg) {
1234 // Can't check initialization for a member of dependent type or when
1235 // any of the arguments are type-dependent expressions.
1236 OwningExprResult Init
1237 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1238 RParenLoc));
1239
1240 // Erase any temporaries within this evaluation context; we're not
1241 // going to track them in the AST, since we'll be rebuilding the
1242 // ASTs during template instantiation.
1243 ExprTemporaries.erase(
1244 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1245 ExprTemporaries.end());
1246
1247 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1248 LParenLoc,
1249 Init.takeAs<Expr>(),
1250 RParenLoc);
1251
Douglas Gregor7ad83902008-11-05 04:29:56 +00001252 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001253
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001254 if (Member->isInvalidDecl())
1255 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001256
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001257 // Initialize the member.
1258 InitializedEntity MemberEntity =
1259 InitializedEntity::InitializeMember(Member, 0);
1260 InitializationKind Kind =
1261 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1262
1263 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1264
1265 OwningExprResult MemberInit =
1266 InitSeq.Perform(*this, MemberEntity, Kind,
1267 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1268 if (MemberInit.isInvalid())
1269 return true;
1270
1271 // C++0x [class.base.init]p7:
1272 // The initialization of each base and member constitutes a
1273 // full-expression.
1274 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1275 if (MemberInit.isInvalid())
1276 return true;
1277
1278 // If we are in a dependent context, template instantiation will
1279 // perform this type-checking again. Just save the arguments that we
1280 // received in a ParenListExpr.
1281 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1282 // of the information that we have about the member
1283 // initializer. However, deconstructing the ASTs is a dicey process,
1284 // and this approach is far more likely to get the corner cases right.
1285 if (CurContext->isDependentContext()) {
1286 // Bump the reference count of all of the arguments.
1287 for (unsigned I = 0; I != NumArgs; ++I)
1288 Args[I]->Retain();
1289
1290 OwningExprResult Init
1291 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1292 RParenLoc));
1293 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1294 LParenLoc,
1295 Init.takeAs<Expr>(),
1296 RParenLoc);
1297 }
1298
Douglas Gregor802ab452009-12-02 22:36:29 +00001299 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001300 LParenLoc,
1301 MemberInit.takeAs<Expr>(),
1302 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001303}
1304
1305Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001306Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001307 Expr **Args, unsigned NumArgs,
1308 SourceLocation LParenLoc, SourceLocation RParenLoc,
1309 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001310 bool HasDependentArg = false;
1311 for (unsigned i = 0; i < NumArgs; i++)
1312 HasDependentArg |= Args[i]->isTypeDependent();
1313
John McCalla93c9342009-12-07 02:54:59 +00001314 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001315 if (BaseType->isDependentType() || HasDependentArg) {
1316 // Can't check initialization for a base of dependent type or when
1317 // any of the arguments are type-dependent expressions.
1318 OwningExprResult BaseInit
1319 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1320 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001321
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001322 // Erase any temporaries within this evaluation context; we're not
1323 // going to track them in the AST, since we'll be rebuilding the
1324 // ASTs during template instantiation.
1325 ExprTemporaries.erase(
1326 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1327 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001329 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1330 LParenLoc,
1331 BaseInit.takeAs<Expr>(),
1332 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001333 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001334
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001335 if (!BaseType->isRecordType())
1336 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1337 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1338
1339 // C++ [class.base.init]p2:
1340 // [...] Unless the mem-initializer-id names a nonstatic data
1341 // member of the constructor’s class or a direct or virtual base
1342 // of that class, the mem-initializer is ill-formed. A
1343 // mem-initializer-list can initialize a base class using any
1344 // name that denotes that base class type.
1345
1346 // Check for direct and virtual base classes.
1347 const CXXBaseSpecifier *DirectBaseSpec = 0;
1348 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1349 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1350 VirtualBaseSpec);
1351
1352 // C++ [base.class.init]p2:
1353 // If a mem-initializer-id is ambiguous because it designates both
1354 // a direct non-virtual base class and an inherited virtual base
1355 // class, the mem-initializer is ill-formed.
1356 if (DirectBaseSpec && VirtualBaseSpec)
1357 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1358 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1359 // C++ [base.class.init]p2:
1360 // Unless the mem-initializer-id names a nonstatic data membeer of the
1361 // constructor's class ot a direst or virtual base of that class, the
1362 // mem-initializer is ill-formed.
1363 if (!DirectBaseSpec && !VirtualBaseSpec)
1364 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1365 << BaseType << ClassDecl->getNameAsCString()
1366 << BaseTInfo->getTypeLoc().getSourceRange();
1367
1368 CXXBaseSpecifier *BaseSpec
1369 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1370 if (!BaseSpec)
1371 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1372
1373 // Initialize the base.
1374 InitializedEntity BaseEntity =
1375 InitializedEntity::InitializeBase(Context, BaseSpec);
1376 InitializationKind Kind =
1377 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1378
1379 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1380
1381 OwningExprResult BaseInit =
1382 InitSeq.Perform(*this, BaseEntity, Kind,
1383 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1384 if (BaseInit.isInvalid())
1385 return true;
1386
1387 // C++0x [class.base.init]p7:
1388 // The initialization of each base and member constitutes a
1389 // full-expression.
1390 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1391 if (BaseInit.isInvalid())
1392 return true;
1393
1394 // If we are in a dependent context, template instantiation will
1395 // perform this type-checking again. Just save the arguments that we
1396 // received in a ParenListExpr.
1397 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1398 // of the information that we have about the base
1399 // initializer. However, deconstructing the ASTs is a dicey process,
1400 // and this approach is far more likely to get the corner cases right.
1401 if (CurContext->isDependentContext()) {
1402 // Bump the reference count of all of the arguments.
1403 for (unsigned I = 0; I != NumArgs; ++I)
1404 Args[I]->Retain();
1405
1406 OwningExprResult Init
1407 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1408 RParenLoc));
1409 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1410 LParenLoc,
1411 Init.takeAs<Expr>(),
1412 RParenLoc);
1413 }
1414
1415 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1416 LParenLoc,
1417 BaseInit.takeAs<Expr>(),
1418 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001419}
1420
Eli Friedman80c30da2009-11-09 19:20:36 +00001421bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001422Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001423 CXXBaseOrMemberInitializer **Initializers,
1424 unsigned NumInitializers,
1425 bool IsImplicitConstructor,
1426 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001427 // We need to build the initializer AST according to order of construction
1428 // and not what user specified in the Initializers list.
1429 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1430 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1431 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1432 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001433 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001435 for (unsigned i = 0; i < NumInitializers; i++) {
1436 CXXBaseOrMemberInitializer *Member = Initializers[i];
1437 if (Member->isBaseInitializer()) {
1438 if (Member->getBaseClass()->isDependentType())
1439 HasDependentBaseInit = true;
1440 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1441 } else {
1442 AllBaseFields[Member->getMember()] = Member;
1443 }
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001446 if (HasDependentBaseInit) {
1447 // FIXME. This does not preserve the ordering of the initializers.
1448 // Try (with -Wreorder)
1449 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001450 // template<class X> struct B : A<X> {
1451 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001452 // int x1;
1453 // };
1454 // B<int> x;
1455 // On seeing one dependent type, we should essentially exit this routine
1456 // while preserving user-declared initializer list. When this routine is
1457 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001458 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460 // If we have a dependent base initialization, we can't determine the
1461 // association between initializers and bases; just dump the known
1462 // initializers into the list, and don't try to deal with other bases.
1463 for (unsigned i = 0; i < NumInitializers; i++) {
1464 CXXBaseOrMemberInitializer *Member = Initializers[i];
1465 if (Member->isBaseInitializer())
1466 AllToInit.push_back(Member);
1467 }
1468 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001469 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1470
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001471 // Push virtual bases before others.
1472 for (CXXRecordDecl::base_class_iterator VBase =
1473 ClassDecl->vbases_begin(),
1474 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1475 if (VBase->getType()->isDependentType())
1476 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001477 if (CXXBaseOrMemberInitializer *Value
1478 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001479 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001480 } else if (!AnyErrors) {
1481 InitializedEntity InitEntity
1482 = InitializedEntity::InitializeBase(Context, VBase);
1483 InitializationKind InitKind
1484 = InitializationKind::CreateDefault(Constructor->getLocation());
1485 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1486 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1487 MultiExprArg(*this, 0, 0));
1488 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1489 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001490 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001491 continue;
1492 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001493
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001494 // Don't attach synthesized base initializers in a dependent
1495 // context; they'll be checked again at template instantiation
1496 // time.
1497 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001498 continue;
1499
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001500 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001501 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001502 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001503 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001504 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001505 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001506 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001507 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001508 }
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001511 for (CXXRecordDecl::base_class_iterator Base =
1512 ClassDecl->bases_begin(),
1513 E = ClassDecl->bases_end(); Base != E; ++Base) {
1514 // Virtuals are in the virtual base list and already constructed.
1515 if (Base->isVirtual())
1516 continue;
1517 // Skip dependent types.
1518 if (Base->getType()->isDependentType())
1519 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001520 if (CXXBaseOrMemberInitializer *Value
1521 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001522 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001523 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001524 else if (!AnyErrors) {
1525 InitializedEntity InitEntity
1526 = InitializedEntity::InitializeBase(Context, Base);
1527 InitializationKind InitKind
1528 = InitializationKind::CreateDefault(Constructor->getLocation());
1529 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1530 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1531 MultiExprArg(*this, 0, 0));
1532 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1533 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001534 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001535 continue;
1536 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001537
1538 // Don't attach synthesized base initializers in a dependent
1539 // context; they'll be regenerated at template instantiation
1540 // time.
1541 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001542 continue;
1543
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001544 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001545 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001546 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001547 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001548 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001549 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001550 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001551 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001552 }
1553 }
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001556 // non-static data members.
1557 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1558 E = ClassDecl->field_end(); Field != E; ++Field) {
1559 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001560 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001561 Field->getType()->getAs<RecordType>()) {
1562 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001563 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001564 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001565 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1566 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1567 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1568 // set to the anonymous union data member used in the initializer
1569 // list.
1570 Value->setMember(*Field);
1571 Value->setAnonUnionMember(*FA);
1572 AllToInit.push_back(Value);
1573 break;
1574 }
1575 }
1576 }
1577 continue;
1578 }
1579 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1580 AllToInit.push_back(Value);
1581 continue;
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001584 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001585 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001586
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001587 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001588 if (FT->getAs<RecordType>()) {
1589 InitializedEntity InitEntity
1590 = InitializedEntity::InitializeMember(*Field);
1591 InitializationKind InitKind
1592 = InitializationKind::CreateDefault(Constructor->getLocation());
1593
1594 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1595 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1596 MultiExprArg(*this, 0, 0));
1597 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1598 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001599 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001600 continue;
1601 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001602
1603 // Don't attach synthesized member initializers in a dependent
1604 // context; they'll be regenerated a template instantiation
1605 // time.
1606 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001607 continue;
1608
Mike Stump1eb44332009-09-09 15:08:12 +00001609 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001610 new (Context) CXXBaseOrMemberInitializer(Context,
1611 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001612 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001613 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001614 SourceLocation());
1615
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001616 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001617 }
1618 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001619 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001620 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1621 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001622 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001623 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001624 }
1625 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001626 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001627 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1628 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001629 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001630 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001631 }
1632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001634 NumInitializers = AllToInit.size();
1635 if (NumInitializers > 0) {
1636 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1637 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1638 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001640 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001641 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1642 CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1643 baseOrMemberInitializers[Idx] = Member;
1644 if (!Member->isBaseInitializer())
1645 continue;
1646 const Type *BaseType = Member->getBaseClass();
1647 const RecordType *RT = BaseType->getAs<RecordType>();
1648 if (!RT)
1649 continue;
1650 CXXRecordDecl *BaseClassDecl =
1651 cast<CXXRecordDecl>(RT->getDecl());
1652 if (BaseClassDecl->hasTrivialDestructor())
1653 continue;
1654 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1655 MarkDeclarationReferenced(Constructor->getLocation(), DD);
1656 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001657 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001658
1659 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001660}
1661
Eli Friedman6347f422009-07-21 19:28:10 +00001662static void *GetKeyForTopLevelField(FieldDecl *Field) {
1663 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001664 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001665 if (RT->getDecl()->isAnonymousStructOrUnion())
1666 return static_cast<void *>(RT->getDecl());
1667 }
1668 return static_cast<void *>(Field);
1669}
1670
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001671static void *GetKeyForBase(QualType BaseType) {
1672 if (const RecordType *RT = BaseType->getAs<RecordType>())
1673 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001675 assert(0 && "Unexpected base type!");
1676 return 0;
1677}
1678
Mike Stump1eb44332009-09-09 15:08:12 +00001679static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001680 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001681 // For fields injected into the class via declaration of an anonymous union,
1682 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001683 if (Member->isMemberInitializer()) {
1684 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Eli Friedman49c16da2009-11-09 01:05:47 +00001686 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001687 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001688 // in AnonUnionMember field.
1689 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1690 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001691 if (Field->getDeclContext()->isRecord()) {
1692 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1693 if (RD->isAnonymousStructOrUnion())
1694 return static_cast<void *>(RD);
1695 }
1696 return static_cast<void *>(Field);
1697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001699 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001700}
1701
John McCall6aee6212009-11-04 23:13:52 +00001702/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001703void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001704 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001705 MemInitTy **MemInits, unsigned NumMemInits,
1706 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001707 if (!ConstructorDecl)
1708 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001709
1710 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
1712 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001713 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Anders Carlssona7b35212009-03-25 02:58:17 +00001715 if (!Constructor) {
1716 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1717 return;
1718 }
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001720 if (!Constructor->isDependentContext()) {
1721 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1722 bool err = false;
1723 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001724 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001725 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1726 void *KeyToMember = GetKeyForMember(Member);
1727 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1728 if (!PrevMember) {
1729 PrevMember = Member;
1730 continue;
1731 }
1732 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001733 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001734 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001735 << Field->getNameAsString()
1736 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001737 else {
1738 Type *BaseClass = Member->getBaseClass();
1739 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001740 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001741 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001742 << QualType(BaseClass, 0)
1743 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001744 }
1745 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1746 << 0;
1747 err = true;
1748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001750 if (err)
1751 return;
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Eli Friedman49c16da2009-11-09 01:05:47 +00001754 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001755 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001756 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001758 if (Constructor->isDependentContext())
1759 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001760
1761 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001762 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001763 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001764 Diagnostic::Ignored)
1765 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001767 // Also issue warning if order of ctor-initializer list does not match order
1768 // of 1) base class declarations and 2) order of non-static data members.
1769 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001771 CXXRecordDecl *ClassDecl
1772 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1773 // Push virtual bases before others.
1774 for (CXXRecordDecl::base_class_iterator VBase =
1775 ClassDecl->vbases_begin(),
1776 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001777 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1780 E = ClassDecl->bases_end(); Base != E; ++Base) {
1781 // Virtuals are alread in the virtual base list and are constructed
1782 // first.
1783 if (Base->isVirtual())
1784 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001785 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001788 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1789 E = ClassDecl->field_end(); Field != E; ++Field)
1790 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001792 int Last = AllBaseOrMembers.size();
1793 int curIndex = 0;
1794 CXXBaseOrMemberInitializer *PrevMember = 0;
1795 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001796 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001797 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1798 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001799
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001800 for (; curIndex < Last; curIndex++)
1801 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1802 break;
1803 if (curIndex == Last) {
1804 assert(PrevMember && "Member not in member list?!");
1805 // Initializer as specified in ctor-initializer list is out of order.
1806 // Issue a warning diagnostic.
1807 if (PrevMember->isBaseInitializer()) {
1808 // Diagnostics is for an initialized base class.
1809 Type *BaseClass = PrevMember->getBaseClass();
1810 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001811 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001812 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001813 } else {
1814 FieldDecl *Field = PrevMember->getMember();
1815 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001816 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001817 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001818 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001819 // Also the note!
1820 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001821 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001822 diag::note_fieldorbase_initialized_here) << 0
1823 << Field->getNameAsString();
1824 else {
1825 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001826 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001827 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001828 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001829 }
1830 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001831 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001832 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001833 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001834 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001835 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001836}
1837
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001838void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001839Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1840 // Ignore dependent destructors.
1841 if (Destructor->isDependentContext())
1842 return;
1843
1844 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Anders Carlsson9f853df2009-11-17 04:44:12 +00001846 // Non-static data members.
1847 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1848 E = ClassDecl->field_end(); I != E; ++I) {
1849 FieldDecl *Field = *I;
1850
1851 QualType FieldType = Context.getBaseElementType(Field->getType());
1852
1853 const RecordType* RT = FieldType->getAs<RecordType>();
1854 if (!RT)
1855 continue;
1856
1857 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1858 if (FieldClassDecl->hasTrivialDestructor())
1859 continue;
1860
1861 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1862 MarkDeclarationReferenced(Destructor->getLocation(),
1863 const_cast<CXXDestructorDecl*>(Dtor));
1864 }
1865
1866 // Bases.
1867 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1868 E = ClassDecl->bases_end(); Base != E; ++Base) {
1869 // Ignore virtual bases.
1870 if (Base->isVirtual())
1871 continue;
1872
1873 // Ignore trivial destructors.
1874 CXXRecordDecl *BaseClassDecl
1875 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1876 if (BaseClassDecl->hasTrivialDestructor())
1877 continue;
1878
1879 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1880 MarkDeclarationReferenced(Destructor->getLocation(),
1881 const_cast<CXXDestructorDecl*>(Dtor));
1882 }
1883
1884 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001885 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1886 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001887 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001888 CXXRecordDecl *BaseClassDecl
1889 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1890 if (BaseClassDecl->hasTrivialDestructor())
1891 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001892
1893 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1894 MarkDeclarationReferenced(Destructor->getLocation(),
1895 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001896 }
1897}
1898
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001899void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001900 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001901 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001903 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001904
1905 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001906 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001907 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001908}
1909
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001910namespace {
1911 /// PureVirtualMethodCollector - traverses a class and its superclasses
1912 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001913 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001914 ASTContext &Context;
1915
Sebastian Redldfe292d2009-03-22 21:28:55 +00001916 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001917 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001918
1919 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001920 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001922 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001924 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001925 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001926 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001928 MethodList List;
1929 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001931 // Copy the temporary list to methods, and make sure to ignore any
1932 // null entries.
1933 for (size_t i = 0, e = List.size(); i != e; ++i) {
1934 if (List[i])
1935 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001936 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001939 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001941 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1942 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001943 };
Mike Stump1eb44332009-09-09 15:08:12 +00001944
1945 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001946 MethodList& Methods) {
1947 // First, collect the pure virtual methods for the base classes.
1948 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1949 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001950 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001951 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001952 if (BaseDecl && BaseDecl->isAbstract())
1953 Collect(BaseDecl, Methods);
1954 }
1955 }
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001957 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001958 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001960 MethodSetTy OverriddenMethods;
1961 size_t MethodsSize = Methods.size();
1962
Mike Stump1eb44332009-09-09 15:08:12 +00001963 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001964 i != e; ++i) {
1965 // Traverse the record, looking for methods.
1966 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001967 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001968 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001969 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Anders Carlsson27823022009-10-18 19:34:08 +00001971 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001972 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1973 E = MD->end_overridden_methods(); I != E; ++I) {
1974 // Keep track of the overridden methods.
1975 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001976 }
1977 }
1978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
1980 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001981 // overridden.
1982 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1983 if (OverriddenMethods.count(Methods[i]))
1984 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001985 }
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001987 }
1988}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001989
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001990
Mike Stump1eb44332009-09-09 15:08:12 +00001991bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001992 unsigned DiagID, AbstractDiagSelID SelID,
1993 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001994 if (SelID == -1)
1995 return RequireNonAbstractType(Loc, T,
1996 PDiag(DiagID), CurrentRD);
1997 else
1998 return RequireNonAbstractType(Loc, T,
1999 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002000}
2001
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002002bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2003 const PartialDiagnostic &PD,
2004 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002005 if (!getLangOptions().CPlusPlus)
2006 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Anders Carlsson11f21a02009-03-23 19:10:31 +00002008 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002009 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002010 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Ted Kremenek6217b802009-07-29 21:53:49 +00002012 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002013 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002014 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002015 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002017 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002018 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Ted Kremenek6217b802009-07-29 21:53:49 +00002021 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002022 if (!RT)
2023 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
John McCall86ff3082010-02-04 22:26:26 +00002025 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002026
Anders Carlssone65a3c82009-03-24 17:23:42 +00002027 if (CurrentRD && CurrentRD != RD)
2028 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
John McCall86ff3082010-02-04 22:26:26 +00002030 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002031 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002032 return false;
2033
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002034 if (!RD->isAbstract())
2035 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002037 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002039 // Check if we've already emitted the list of pure virtual functions for this
2040 // class.
2041 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2042 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002044 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002045
2046 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002047 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2048 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
2050 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002051 MD->getDeclName();
2052 }
2053
2054 if (!PureVirtualClassDiagSet)
2055 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2056 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002058 return true;
2059}
2060
Anders Carlsson8211eff2009-03-24 01:19:16 +00002061namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002062 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002063 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2064 Sema &SemaRef;
2065 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Anders Carlssone65a3c82009-03-24 17:23:42 +00002067 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002068 bool Invalid = false;
2069
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002070 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2071 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002072 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002073
Anders Carlsson8211eff2009-03-24 01:19:16 +00002074 return Invalid;
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Anders Carlssone65a3c82009-03-24 17:23:42 +00002077 public:
2078 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2079 : SemaRef(SemaRef), AbstractClass(ac) {
2080 Visit(SemaRef.Context.getTranslationUnitDecl());
2081 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002082
Anders Carlssone65a3c82009-03-24 17:23:42 +00002083 bool VisitFunctionDecl(const FunctionDecl *FD) {
2084 if (FD->isThisDeclarationADefinition()) {
2085 // No need to do the check if we're in a definition, because it requires
2086 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002087 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002088 return VisitDeclContext(FD);
2089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Anders Carlssone65a3c82009-03-24 17:23:42 +00002091 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002092 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002093 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002094 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2095 diag::err_abstract_type_in_decl,
2096 Sema::AbstractReturnType,
2097 AbstractClass);
2098
Mike Stump1eb44332009-09-09 15:08:12 +00002099 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002100 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002101 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002102 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002103 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002104 VD->getOriginalType(),
2105 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002106 Sema::AbstractParamType,
2107 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002108 }
2109
2110 return Invalid;
2111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Anders Carlssone65a3c82009-03-24 17:23:42 +00002113 bool VisitDecl(const Decl* D) {
2114 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2115 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Anders Carlssone65a3c82009-03-24 17:23:42 +00002117 return false;
2118 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002119 };
2120}
2121
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002122/// \brief Perform semantic checks on a class definition that has been
2123/// completing, introducing implicitly-declared members, checking for
2124/// abstract types, etc.
2125void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2126 if (!Record || Record->isInvalidDecl())
2127 return;
2128
Eli Friedmanff2d8782009-12-16 20:00:27 +00002129 if (!Record->isDependentType())
2130 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002131
Eli Friedmanff2d8782009-12-16 20:00:27 +00002132 if (Record->isInvalidDecl())
2133 return;
2134
John McCall233a6412010-01-28 07:38:46 +00002135 // Set access bits correctly on the directly-declared conversions.
2136 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2137 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2138 Convs->setAccess(I, (*I)->getAccess());
2139
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002140 if (!Record->isAbstract()) {
2141 // Collect all the pure virtual methods and see if this is an abstract
2142 // class after all.
2143 PureVirtualMethodCollector Collector(Context, Record);
2144 if (!Collector.empty())
2145 Record->setAbstract(true);
2146 }
2147
2148 if (Record->isAbstract())
2149 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002150}
2151
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002152void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002153 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002154 SourceLocation LBrac,
2155 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002156 if (!TagDecl)
2157 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Douglas Gregor42af25f2009-05-11 19:58:34 +00002159 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002160
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002161 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002162 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002163 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002164
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002165 CheckCompletedCXXClass(
2166 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002167}
2168
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002169/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2170/// special functions, such as the default constructor, copy
2171/// constructor, or destructor, to the given C++ class (C++
2172/// [special]p1). This routine can only be executed just before the
2173/// definition of the class is complete.
2174void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002175 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002176 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002177
Sebastian Redl465226e2009-05-27 22:11:52 +00002178 // FIXME: Implicit declarations have exception specifications, which are
2179 // the union of the specifications of the implicitly called functions.
2180
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002181 if (!ClassDecl->hasUserDeclaredConstructor()) {
2182 // C++ [class.ctor]p5:
2183 // A default constructor for a class X is a constructor of class X
2184 // that can be called without an argument. If there is no
2185 // user-declared constructor for class X, a default constructor is
2186 // implicitly declared. An implicitly-declared default constructor
2187 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002188 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002189 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002190 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002191 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002192 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002193 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002194 0, 0, false, 0,
2195 /*FIXME*/false, false,
2196 0, 0, false,
2197 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002198 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002199 /*isExplicit=*/false,
2200 /*isInline=*/true,
2201 /*isImplicitlyDeclared=*/true);
2202 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002203 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002204 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002205 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002206 }
2207
2208 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2209 // C++ [class.copy]p4:
2210 // If the class definition does not explicitly declare a copy
2211 // constructor, one is declared implicitly.
2212
2213 // C++ [class.copy]p5:
2214 // The implicitly-declared copy constructor for a class X will
2215 // have the form
2216 //
2217 // X::X(const X&)
2218 //
2219 // if
2220 bool HasConstCopyConstructor = true;
2221
2222 // -- each direct or virtual base class B of X has a copy
2223 // constructor whose first parameter is of type const B& or
2224 // const volatile B&, and
2225 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2226 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2227 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002228 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002229 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002230 = BaseClassDecl->hasConstCopyConstructor(Context);
2231 }
2232
2233 // -- for all the nonstatic data members of X that are of a
2234 // class type M (or array thereof), each such class type
2235 // has a copy constructor whose first parameter is of type
2236 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002237 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2238 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002239 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002240 QualType FieldType = (*Field)->getType();
2241 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2242 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002243 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002244 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002245 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002246 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002247 = FieldClassDecl->hasConstCopyConstructor(Context);
2248 }
2249 }
2250
Sebastian Redl64b45f72009-01-05 20:52:13 +00002251 // Otherwise, the implicitly declared copy constructor will have
2252 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002253 //
2254 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002255 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002256 if (HasConstCopyConstructor)
2257 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002258 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002259
Sebastian Redl64b45f72009-01-05 20:52:13 +00002260 // An implicitly-declared copy constructor is an inline public
2261 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002262 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002263 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002264 CXXConstructorDecl *CopyConstructor
2265 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002266 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002267 Context.getFunctionType(Context.VoidTy,
2268 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002269 false, 0,
2270 /*FIXME:*/false,
2271 false, 0, 0, false,
2272 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002273 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002274 /*isExplicit=*/false,
2275 /*isInline=*/true,
2276 /*isImplicitlyDeclared=*/true);
2277 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002278 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002279 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002280
2281 // Add the parameter to the constructor.
2282 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2283 ClassDecl->getLocation(),
2284 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002285 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002286 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002287 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002288 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002289 }
2290
Sebastian Redl64b45f72009-01-05 20:52:13 +00002291 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2292 // Note: The following rules are largely analoguous to the copy
2293 // constructor rules. Note that virtual bases are not taken into account
2294 // for determining the argument type of the operator. Note also that
2295 // operators taking an object instead of a reference are allowed.
2296 //
2297 // C++ [class.copy]p10:
2298 // If the class definition does not explicitly declare a copy
2299 // assignment operator, one is declared implicitly.
2300 // The implicitly-defined copy assignment operator for a class X
2301 // will have the form
2302 //
2303 // X& X::operator=(const X&)
2304 //
2305 // if
2306 bool HasConstCopyAssignment = true;
2307
2308 // -- each direct base class B of X has a copy assignment operator
2309 // whose parameter is of type const B&, const volatile B& or B,
2310 // and
2311 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2312 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002313 assert(!Base->getType()->isDependentType() &&
2314 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002315 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002316 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002317 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002318 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002319 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002320 }
2321
2322 // -- for all the nonstatic data members of X that are of a class
2323 // type M (or array thereof), each such class type has a copy
2324 // assignment operator whose parameter is of type const M&,
2325 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002326 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2327 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002328 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002329 QualType FieldType = (*Field)->getType();
2330 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2331 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002332 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002333 const CXXRecordDecl *FieldClassDecl
2334 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002335 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002336 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002337 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002338 }
2339 }
2340
2341 // Otherwise, the implicitly declared copy assignment operator will
2342 // have the form
2343 //
2344 // X& X::operator=(X&)
2345 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002346 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002347 if (HasConstCopyAssignment)
2348 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002349 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002350
2351 // An implicitly-declared copy assignment operator is an inline public
2352 // member of its class.
2353 DeclarationName Name =
2354 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2355 CXXMethodDecl *CopyAssignment =
2356 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2357 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002358 false, 0,
2359 /*FIXME:*/false,
2360 false, 0, 0, false,
2361 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002362 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002363 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002364 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002365 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002366 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002367
2368 // Add the parameter to the operator.
2369 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2370 ClassDecl->getLocation(),
2371 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002372 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002373 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002374 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002375
2376 // Don't call addedAssignmentOperator. There is no way to distinguish an
2377 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002378 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002379 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002380 }
2381
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002382 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002383 // C++ [class.dtor]p2:
2384 // If a class has no user-declared destructor, a destructor is
2385 // declared implicitly. An implicitly-declared destructor is an
2386 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002387 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002388 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002389 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002390 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002391 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002392 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002393 0, 0, false, 0,
2394 /*FIXME:*/false,
2395 false, 0, 0, false,
2396 CC_Default),
Douglas Gregor42a552f2008-11-05 20:51:48 +00002397 /*isInline=*/true,
2398 /*isImplicitlyDeclared=*/true);
2399 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002400 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002401 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002402 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002403
2404 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002405 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002406}
2407
Douglas Gregor6569d682009-05-27 23:11:45 +00002408void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002409 Decl *D = TemplateD.getAs<Decl>();
2410 if (!D)
2411 return;
2412
2413 TemplateParameterList *Params = 0;
2414 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2415 Params = Template->getTemplateParameters();
2416 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2417 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2418 Params = PartialSpec->getTemplateParameters();
2419 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002420 return;
2421
Douglas Gregor6569d682009-05-27 23:11:45 +00002422 for (TemplateParameterList::iterator Param = Params->begin(),
2423 ParamEnd = Params->end();
2424 Param != ParamEnd; ++Param) {
2425 NamedDecl *Named = cast<NamedDecl>(*Param);
2426 if (Named->getDeclName()) {
2427 S->AddDecl(DeclPtrTy::make(Named));
2428 IdResolver.AddDecl(Named);
2429 }
2430 }
2431}
2432
John McCall7a1dc562009-12-19 10:49:29 +00002433void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2434 if (!RecordD) return;
2435 AdjustDeclIfTemplate(RecordD);
2436 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2437 PushDeclContext(S, Record);
2438}
2439
2440void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2441 if (!RecordD) return;
2442 PopDeclContext();
2443}
2444
Douglas Gregor72b505b2008-12-16 21:30:33 +00002445/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2446/// parsing a top-level (non-nested) C++ class, and we are now
2447/// parsing those parts of the given Method declaration that could
2448/// not be parsed earlier (C++ [class.mem]p2), such as default
2449/// arguments. This action should enter the scope of the given
2450/// Method declaration as if we had just parsed the qualified method
2451/// name. However, it should not bring the parameters into scope;
2452/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002453void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002454}
2455
2456/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2457/// C++ method declaration. We're (re-)introducing the given
2458/// function parameter into scope for use in parsing later parts of
2459/// the method declaration. For example, we could see an
2460/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002461void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002462 if (!ParamD)
2463 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002464
Chris Lattnerb28317a2009-03-28 19:18:32 +00002465 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002466
2467 // If this parameter has an unparsed default argument, clear it out
2468 // to make way for the parsed default argument.
2469 if (Param->hasUnparsedDefaultArg())
2470 Param->setDefaultArg(0);
2471
Chris Lattnerb28317a2009-03-28 19:18:32 +00002472 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002473 if (Param->getDeclName())
2474 IdResolver.AddDecl(Param);
2475}
2476
2477/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2478/// processing the delayed method declaration for Method. The method
2479/// declaration is now considered finished. There may be a separate
2480/// ActOnStartOfFunctionDef action later (not necessarily
2481/// immediately!) for this method, if it was also defined inside the
2482/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002483void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002484 if (!MethodD)
2485 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002487 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Chris Lattnerb28317a2009-03-28 19:18:32 +00002489 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002490
2491 // Now that we have our default arguments, check the constructor
2492 // again. It could produce additional diagnostics or affect whether
2493 // the class has implicitly-declared destructors, among other
2494 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002495 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2496 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002497
2498 // Check the default arguments, which we may have added.
2499 if (!Method->isInvalidDecl())
2500 CheckCXXDefaultArguments(Method);
2501}
2502
Douglas Gregor42a552f2008-11-05 20:51:48 +00002503/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002504/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002505/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002506/// emit diagnostics and set the invalid bit to true. In any case, the type
2507/// will be updated to reflect a well-formed type for the constructor and
2508/// returned.
2509QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2510 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002511 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002512
2513 // C++ [class.ctor]p3:
2514 // A constructor shall not be virtual (10.3) or static (9.4). A
2515 // constructor can be invoked for a const, volatile or const
2516 // volatile object. A constructor shall not be declared const,
2517 // volatile, or const volatile (9.3.2).
2518 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002519 if (!D.isInvalidType())
2520 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2521 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2522 << SourceRange(D.getIdentifierLoc());
2523 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002524 }
2525 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002526 if (!D.isInvalidType())
2527 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2528 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2529 << SourceRange(D.getIdentifierLoc());
2530 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002531 SC = FunctionDecl::None;
2532 }
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Chris Lattner65401802009-04-25 08:28:21 +00002534 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2535 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002536 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002537 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2538 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002539 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002540 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2541 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002542 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002543 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2544 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002545 }
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Douglas Gregor42a552f2008-11-05 20:51:48 +00002547 // Rebuild the function type "R" without any type qualifiers (in
2548 // case any of the errors above fired) and with "void" as the
2549 // return type, since constructors don't have return types. We
2550 // *always* have to do this, because GetTypeForDeclarator will
2551 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002552 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002553 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2554 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002555 Proto->isVariadic(), 0,
2556 Proto->hasExceptionSpec(),
2557 Proto->hasAnyExceptionSpec(),
2558 Proto->getNumExceptions(),
2559 Proto->exception_begin(),
2560 Proto->getNoReturnAttr(),
2561 Proto->getCallConv());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002562}
2563
Douglas Gregor72b505b2008-12-16 21:30:33 +00002564/// CheckConstructor - Checks a fully-formed constructor for
2565/// well-formedness, issuing any diagnostics required. Returns true if
2566/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002567void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002568 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002569 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2570 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002571 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002572
2573 // C++ [class.copy]p3:
2574 // A declaration of a constructor for a class X is ill-formed if
2575 // its first parameter is of type (optionally cv-qualified) X and
2576 // either there are no other parameters or else all other
2577 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002578 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002579 ((Constructor->getNumParams() == 1) ||
2580 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002581 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2582 Constructor->getTemplateSpecializationKind()
2583 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002584 QualType ParamType = Constructor->getParamDecl(0)->getType();
2585 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2586 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002587 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2588 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002589 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002590
2591 // FIXME: Rather that making the constructor invalid, we should endeavor
2592 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002593 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002594 }
2595 }
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Douglas Gregor72b505b2008-12-16 21:30:33 +00002597 // Notify the class that we've added a constructor.
2598 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002599}
2600
Anders Carlsson37909802009-11-30 21:24:50 +00002601/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2602/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002603bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002604 CXXRecordDecl *RD = Destructor->getParent();
2605
2606 if (Destructor->isVirtual()) {
2607 SourceLocation Loc;
2608
2609 if (!Destructor->isImplicit())
2610 Loc = Destructor->getLocation();
2611 else
2612 Loc = RD->getLocation();
2613
2614 // If we have a virtual destructor, look up the deallocation function
2615 FunctionDecl *OperatorDelete = 0;
2616 DeclarationName Name =
2617 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002618 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002619 return true;
2620
2621 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002622 }
Anders Carlsson37909802009-11-30 21:24:50 +00002623
2624 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002625}
2626
Mike Stump1eb44332009-09-09 15:08:12 +00002627static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002628FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2629 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2630 FTI.ArgInfo[0].Param &&
2631 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2632}
2633
Douglas Gregor42a552f2008-11-05 20:51:48 +00002634/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2635/// the well-formednes of the destructor declarator @p D with type @p
2636/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002637/// emit diagnostics and set the declarator to invalid. Even if this happens,
2638/// will be updated to reflect a well-formed type for the destructor and
2639/// returned.
2640QualType Sema::CheckDestructorDeclarator(Declarator &D,
2641 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002642 // C++ [class.dtor]p1:
2643 // [...] A typedef-name that names a class is a class-name
2644 // (7.1.3); however, a typedef-name that names a class shall not
2645 // be used as the identifier in the declarator for a destructor
2646 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002647 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002648 if (isa<TypedefType>(DeclaratorType)) {
2649 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002650 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002651 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002652 }
2653
2654 // C++ [class.dtor]p2:
2655 // A destructor is used to destroy objects of its class type. A
2656 // destructor takes no parameters, and no return type can be
2657 // specified for it (not even void). The address of a destructor
2658 // shall not be taken. A destructor shall not be static. A
2659 // destructor can be invoked for a const, volatile or const
2660 // volatile object. A destructor shall not be declared const,
2661 // volatile or const volatile (9.3.2).
2662 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002663 if (!D.isInvalidType())
2664 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2665 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2666 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002667 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002668 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002669 }
Chris Lattner65401802009-04-25 08:28:21 +00002670 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002671 // Destructors don't have return types, but the parser will
2672 // happily parse something like:
2673 //
2674 // class X {
2675 // float ~X();
2676 // };
2677 //
2678 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002679 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2680 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2681 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002682 }
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Chris Lattner65401802009-04-25 08:28:21 +00002684 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2685 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002686 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002687 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2688 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002689 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002690 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2691 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002692 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002693 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2694 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002695 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002696 }
2697
2698 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002699 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002700 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2701
2702 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002703 FTI.freeArgs();
2704 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002705 }
2706
Mike Stump1eb44332009-09-09 15:08:12 +00002707 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002708 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002709 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002710 D.setInvalidType();
2711 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002712
2713 // Rebuild the function type "R" without any type qualifiers or
2714 // parameters (in case any of the errors above fired) and with
2715 // "void" as the return type, since destructors don't have return
2716 // types. We *always* have to do this, because GetTypeForDeclarator
2717 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002718 // FIXME: Exceptions!
2719 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2720 false, false, 0, 0, false, CC_Default);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002721}
2722
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002723/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2724/// well-formednes of the conversion function declarator @p D with
2725/// type @p R. If there are any errors in the declarator, this routine
2726/// will emit diagnostics and return true. Otherwise, it will return
2727/// false. Either way, the type @p R will be updated to reflect a
2728/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002729void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002730 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002731 // C++ [class.conv.fct]p1:
2732 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002733 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002734 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002735 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002736 if (!D.isInvalidType())
2737 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2738 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2739 << SourceRange(D.getIdentifierLoc());
2740 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002741 SC = FunctionDecl::None;
2742 }
Chris Lattner6e475012009-04-25 08:35:12 +00002743 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002744 // Conversion functions don't have return types, but the parser will
2745 // happily parse something like:
2746 //
2747 // class X {
2748 // float operator bool();
2749 // };
2750 //
2751 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002752 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2753 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2754 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002755 }
2756
2757 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002758 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002759 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2760
2761 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002762 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002763 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002764 }
2765
Mike Stump1eb44332009-09-09 15:08:12 +00002766 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002767 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002768 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002769 D.setInvalidType();
2770 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002771
2772 // C++ [class.conv.fct]p4:
2773 // The conversion-type-id shall not represent a function type nor
2774 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002775 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002776 if (ConvType->isArrayType()) {
2777 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2778 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002779 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002780 } else if (ConvType->isFunctionType()) {
2781 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2782 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002783 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002784 }
2785
2786 // Rebuild the function type "R" without any parameters (in case any
2787 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002788 // return type.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002789 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002790 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002791 Proto->getTypeQuals(),
2792 Proto->hasExceptionSpec(),
2793 Proto->hasAnyExceptionSpec(),
2794 Proto->getNumExceptions(),
2795 Proto->exception_begin(),
2796 Proto->getNoReturnAttr(),
2797 Proto->getCallConv());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002798
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002799 // C++0x explicit conversion operators.
2800 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002801 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002802 diag::warn_explicit_conversion_functions)
2803 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002804}
2805
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002806/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2807/// the declaration of the given C++ conversion function. This routine
2808/// is responsible for recording the conversion function in the C++
2809/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002810Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002811 assert(Conversion && "Expected to receive a conversion function declaration");
2812
Douglas Gregor9d350972008-12-12 08:25:50 +00002813 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002814
2815 // Make sure we aren't redeclaring the conversion function.
2816 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002817
2818 // C++ [class.conv.fct]p1:
2819 // [...] A conversion function is never used to convert a
2820 // (possibly cv-qualified) object to the (possibly cv-qualified)
2821 // same object type (or a reference to it), to a (possibly
2822 // cv-qualified) base class of that type (or a reference to it),
2823 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002824 // FIXME: Suppress this warning if the conversion function ends up being a
2825 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002826 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002827 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002828 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002829 ConvType = ConvTypeRef->getPointeeType();
2830 if (ConvType->isRecordType()) {
2831 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2832 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002833 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002834 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002835 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002836 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002837 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002838 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002839 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002840 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002841 }
2842
Douglas Gregor48026d22010-01-11 18:40:55 +00002843 if (Conversion->getPrimaryTemplate()) {
2844 // ignore specializations
2845 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002846 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002847 = Conversion->getDescribedFunctionTemplate()) {
2848 if (ClassDecl->replaceConversion(
2849 ConversionTemplate->getPreviousDeclaration(),
2850 ConversionTemplate))
2851 return DeclPtrTy::make(ConversionTemplate);
2852 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2853 Conversion))
John McCallba135432009-11-21 08:51:07 +00002854 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002855 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002856 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002857 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002858 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002859 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002860 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002861
Chris Lattnerb28317a2009-03-28 19:18:32 +00002862 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002863}
2864
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002865//===----------------------------------------------------------------------===//
2866// Namespace Handling
2867//===----------------------------------------------------------------------===//
2868
2869/// ActOnStartNamespaceDef - This is called at the start of a namespace
2870/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002871Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2872 SourceLocation IdentLoc,
2873 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002874 SourceLocation LBrace,
2875 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002876 NamespaceDecl *Namespc =
2877 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2878 Namespc->setLBracLoc(LBrace);
2879
2880 Scope *DeclRegionScope = NamespcScope->getParent();
2881
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002882 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2883
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002884 if (II) {
2885 // C++ [namespace.def]p2:
2886 // The identifier in an original-namespace-definition shall not have been
2887 // previously defined in the declarative region in which the
2888 // original-namespace-definition appears. The identifier in an
2889 // original-namespace-definition is the name of the namespace. Subsequently
2890 // in that declarative region, it is treated as an original-namespace-name.
2891
John McCallf36e02d2009-10-09 21:13:30 +00002892 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002893 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002894 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Douglas Gregor44b43212008-12-11 16:49:14 +00002896 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2897 // This is an extended namespace definition.
2898 // Attach this namespace decl to the chain of extended namespace
2899 // definitions.
2900 OrigNS->setNextNamespace(Namespc);
2901 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002902
Mike Stump1eb44332009-09-09 15:08:12 +00002903 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002904 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002905 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002906 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002907 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002908 } else if (PrevDecl) {
2909 // This is an invalid name redefinition.
2910 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2911 << Namespc->getDeclName();
2912 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2913 Namespc->setInvalidDecl();
2914 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002915 } else if (II->isStr("std") &&
2916 CurContext->getLookupContext()->isTranslationUnit()) {
2917 // This is the first "real" definition of the namespace "std", so update
2918 // our cache of the "std" namespace to point at this definition.
2919 if (StdNamespace) {
2920 // We had already defined a dummy namespace "std". Link this new
2921 // namespace definition to the dummy namespace "std".
2922 StdNamespace->setNextNamespace(Namespc);
2923 StdNamespace->setLocation(IdentLoc);
2924 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2925 }
2926
2927 // Make our StdNamespace cache point at the first real definition of the
2928 // "std" namespace.
2929 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002930 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002931
2932 PushOnScopeChains(Namespc, DeclRegionScope);
2933 } else {
John McCall9aeed322009-10-01 00:25:31 +00002934 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002935 assert(Namespc->isAnonymousNamespace());
2936 CurContext->addDecl(Namespc);
2937
2938 // Link the anonymous namespace into its parent.
2939 NamespaceDecl *PrevDecl;
2940 DeclContext *Parent = CurContext->getLookupContext();
2941 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2942 PrevDecl = TU->getAnonymousNamespace();
2943 TU->setAnonymousNamespace(Namespc);
2944 } else {
2945 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2946 PrevDecl = ND->getAnonymousNamespace();
2947 ND->setAnonymousNamespace(Namespc);
2948 }
2949
2950 // Link the anonymous namespace with its previous declaration.
2951 if (PrevDecl) {
2952 assert(PrevDecl->isAnonymousNamespace());
2953 assert(!PrevDecl->getNextNamespace());
2954 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2955 PrevDecl->setNextNamespace(Namespc);
2956 }
John McCall9aeed322009-10-01 00:25:31 +00002957
2958 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2959 // behaves as if it were replaced by
2960 // namespace unique { /* empty body */ }
2961 // using namespace unique;
2962 // namespace unique { namespace-body }
2963 // where all occurrences of 'unique' in a translation unit are
2964 // replaced by the same identifier and this identifier differs
2965 // from all other identifiers in the entire program.
2966
2967 // We just create the namespace with an empty name and then add an
2968 // implicit using declaration, just like the standard suggests.
2969 //
2970 // CodeGen enforces the "universally unique" aspect by giving all
2971 // declarations semantically contained within an anonymous
2972 // namespace internal linkage.
2973
John McCall5fdd7642009-12-16 02:06:49 +00002974 if (!PrevDecl) {
2975 UsingDirectiveDecl* UD
2976 = UsingDirectiveDecl::Create(Context, CurContext,
2977 /* 'using' */ LBrace,
2978 /* 'namespace' */ SourceLocation(),
2979 /* qualifier */ SourceRange(),
2980 /* NNS */ NULL,
2981 /* identifier */ SourceLocation(),
2982 Namespc,
2983 /* Ancestor */ CurContext);
2984 UD->setImplicit();
2985 CurContext->addDecl(UD);
2986 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002987 }
2988
2989 // Although we could have an invalid decl (i.e. the namespace name is a
2990 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002991 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2992 // for the namespace has the declarations that showed up in that particular
2993 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002994 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002995 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002996}
2997
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002998/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2999/// is a namespace alias, returns the namespace it points to.
3000static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3001 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3002 return AD->getNamespace();
3003 return dyn_cast_or_null<NamespaceDecl>(D);
3004}
3005
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003006/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3007/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003008void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3009 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003010 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3011 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3012 Namespc->setRBracLoc(RBrace);
3013 PopDeclContext();
3014}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003015
Chris Lattnerb28317a2009-03-28 19:18:32 +00003016Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3017 SourceLocation UsingLoc,
3018 SourceLocation NamespcLoc,
3019 const CXXScopeSpec &SS,
3020 SourceLocation IdentLoc,
3021 IdentifierInfo *NamespcName,
3022 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003023 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3024 assert(NamespcName && "Invalid NamespcName.");
3025 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003026 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003027
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003028 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003029
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003030 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003031 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3032 LookupParsedName(R, S, &SS);
3033 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003034 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003035
John McCallf36e02d2009-10-09 21:13:30 +00003036 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003037 NamedDecl *Named = R.getFoundDecl();
3038 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3039 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003040 // C++ [namespace.udir]p1:
3041 // A using-directive specifies that the names in the nominated
3042 // namespace can be used in the scope in which the
3043 // using-directive appears after the using-directive. During
3044 // unqualified name lookup (3.4.1), the names appear as if they
3045 // were declared in the nearest enclosing namespace which
3046 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003047 // namespace. [Note: in this context, "contains" means "contains
3048 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003049
3050 // Find enclosing context containing both using-directive and
3051 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003052 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003053 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3054 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3055 CommonAncestor = CommonAncestor->getParent();
3056
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003057 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003058 SS.getRange(),
3059 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003060 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003061 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003062 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003063 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003064 }
3065
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003066 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003067 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003068 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003069}
3070
3071void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3072 // If scope has associated entity, then using directive is at namespace
3073 // or translation unit scope. We add UsingDirectiveDecls, into
3074 // it's lookup structure.
3075 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003076 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003077 else
3078 // Otherwise it is block-sope. using-directives will affect lookup
3079 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003080 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003081}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003082
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003083
3084Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003085 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003086 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003087 SourceLocation UsingLoc,
3088 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003089 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003090 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003091 bool IsTypeName,
3092 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003093 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Douglas Gregor12c118a2009-11-04 16:30:06 +00003095 switch (Name.getKind()) {
3096 case UnqualifiedId::IK_Identifier:
3097 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003098 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003099 case UnqualifiedId::IK_ConversionFunctionId:
3100 break;
3101
3102 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003103 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003104 // C++0x inherited constructors.
3105 if (getLangOptions().CPlusPlus0x) break;
3106
Douglas Gregor12c118a2009-11-04 16:30:06 +00003107 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3108 << SS.getRange();
3109 return DeclPtrTy();
3110
3111 case UnqualifiedId::IK_DestructorName:
3112 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3113 << SS.getRange();
3114 return DeclPtrTy();
3115
3116 case UnqualifiedId::IK_TemplateId:
3117 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3118 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3119 return DeclPtrTy();
3120 }
3121
3122 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003123 if (!TargetName)
3124 return DeclPtrTy();
3125
John McCall60fa3cf2009-12-11 02:10:03 +00003126 // Warn about using declarations.
3127 // TODO: store that the declaration was written without 'using' and
3128 // talk about access decls instead of using decls in the
3129 // diagnostics.
3130 if (!HasUsingKeyword) {
3131 UsingLoc = Name.getSourceRange().getBegin();
3132
3133 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3134 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3135 "using ");
3136 }
3137
John McCall9488ea12009-11-17 05:59:44 +00003138 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003139 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003140 TargetName, AttrList,
3141 /* IsInstantiation */ false,
3142 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003143 if (UD)
3144 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Anders Carlssonc72160b2009-08-28 05:40:36 +00003146 return DeclPtrTy::make(UD);
3147}
3148
John McCall9f54ad42009-12-10 09:41:52 +00003149/// Determines whether to create a using shadow decl for a particular
3150/// decl, given the set of decls existing prior to this using lookup.
3151bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3152 const LookupResult &Previous) {
3153 // Diagnose finding a decl which is not from a base class of the
3154 // current class. We do this now because there are cases where this
3155 // function will silently decide not to build a shadow decl, which
3156 // will pre-empt further diagnostics.
3157 //
3158 // We don't need to do this in C++0x because we do the check once on
3159 // the qualifier.
3160 //
3161 // FIXME: diagnose the following if we care enough:
3162 // struct A { int foo; };
3163 // struct B : A { using A::foo; };
3164 // template <class T> struct C : A {};
3165 // template <class T> struct D : C<T> { using B::foo; } // <---
3166 // This is invalid (during instantiation) in C++03 because B::foo
3167 // resolves to the using decl in B, which is not a base class of D<T>.
3168 // We can't diagnose it immediately because C<T> is an unknown
3169 // specialization. The UsingShadowDecl in D<T> then points directly
3170 // to A::foo, which will look well-formed when we instantiate.
3171 // The right solution is to not collapse the shadow-decl chain.
3172 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3173 DeclContext *OrigDC = Orig->getDeclContext();
3174
3175 // Handle enums and anonymous structs.
3176 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3177 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3178 while (OrigRec->isAnonymousStructOrUnion())
3179 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3180
3181 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3182 if (OrigDC == CurContext) {
3183 Diag(Using->getLocation(),
3184 diag::err_using_decl_nested_name_specifier_is_current_class)
3185 << Using->getNestedNameRange();
3186 Diag(Orig->getLocation(), diag::note_using_decl_target);
3187 return true;
3188 }
3189
3190 Diag(Using->getNestedNameRange().getBegin(),
3191 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3192 << Using->getTargetNestedNameDecl()
3193 << cast<CXXRecordDecl>(CurContext)
3194 << Using->getNestedNameRange();
3195 Diag(Orig->getLocation(), diag::note_using_decl_target);
3196 return true;
3197 }
3198 }
3199
3200 if (Previous.empty()) return false;
3201
3202 NamedDecl *Target = Orig;
3203 if (isa<UsingShadowDecl>(Target))
3204 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3205
John McCalld7533ec2009-12-11 02:33:26 +00003206 // If the target happens to be one of the previous declarations, we
3207 // don't have a conflict.
3208 //
3209 // FIXME: but we might be increasing its access, in which case we
3210 // should redeclare it.
3211 NamedDecl *NonTag = 0, *Tag = 0;
3212 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3213 I != E; ++I) {
3214 NamedDecl *D = (*I)->getUnderlyingDecl();
3215 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3216 return false;
3217
3218 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3219 }
3220
John McCall9f54ad42009-12-10 09:41:52 +00003221 if (Target->isFunctionOrFunctionTemplate()) {
3222 FunctionDecl *FD;
3223 if (isa<FunctionTemplateDecl>(Target))
3224 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3225 else
3226 FD = cast<FunctionDecl>(Target);
3227
3228 NamedDecl *OldDecl = 0;
3229 switch (CheckOverload(FD, Previous, OldDecl)) {
3230 case Ovl_Overload:
3231 return false;
3232
3233 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003234 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003235 break;
3236
3237 // We found a decl with the exact signature.
3238 case Ovl_Match:
3239 if (isa<UsingShadowDecl>(OldDecl)) {
3240 // Silently ignore the possible conflict.
3241 return false;
3242 }
3243
3244 // If we're in a record, we want to hide the target, so we
3245 // return true (without a diagnostic) to tell the caller not to
3246 // build a shadow decl.
3247 if (CurContext->isRecord())
3248 return true;
3249
3250 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003251 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003252 break;
3253 }
3254
3255 Diag(Target->getLocation(), diag::note_using_decl_target);
3256 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3257 return true;
3258 }
3259
3260 // Target is not a function.
3261
John McCall9f54ad42009-12-10 09:41:52 +00003262 if (isa<TagDecl>(Target)) {
3263 // No conflict between a tag and a non-tag.
3264 if (!Tag) return false;
3265
John McCall41ce66f2009-12-10 19:51:03 +00003266 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003267 Diag(Target->getLocation(), diag::note_using_decl_target);
3268 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3269 return true;
3270 }
3271
3272 // No conflict between a tag and a non-tag.
3273 if (!NonTag) return false;
3274
John McCall41ce66f2009-12-10 19:51:03 +00003275 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003276 Diag(Target->getLocation(), diag::note_using_decl_target);
3277 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3278 return true;
3279}
3280
John McCall9488ea12009-11-17 05:59:44 +00003281/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003282UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003283 UsingDecl *UD,
3284 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003285
3286 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003287 NamedDecl *Target = Orig;
3288 if (isa<UsingShadowDecl>(Target)) {
3289 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3290 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003291 }
3292
3293 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003294 = UsingShadowDecl::Create(Context, CurContext,
3295 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003296 UD->addShadowDecl(Shadow);
3297
3298 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003299 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003300 else
John McCall604e7f12009-12-08 07:46:18 +00003301 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003302 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003303
John McCall604e7f12009-12-08 07:46:18 +00003304 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3305 Shadow->setInvalidDecl();
3306
John McCall9f54ad42009-12-10 09:41:52 +00003307 return Shadow;
3308}
John McCall604e7f12009-12-08 07:46:18 +00003309
John McCall9f54ad42009-12-10 09:41:52 +00003310/// Hides a using shadow declaration. This is required by the current
3311/// using-decl implementation when a resolvable using declaration in a
3312/// class is followed by a declaration which would hide or override
3313/// one or more of the using decl's targets; for example:
3314///
3315/// struct Base { void foo(int); };
3316/// struct Derived : Base {
3317/// using Base::foo;
3318/// void foo(int);
3319/// };
3320///
3321/// The governing language is C++03 [namespace.udecl]p12:
3322///
3323/// When a using-declaration brings names from a base class into a
3324/// derived class scope, member functions in the derived class
3325/// override and/or hide member functions with the same name and
3326/// parameter types in a base class (rather than conflicting).
3327///
3328/// There are two ways to implement this:
3329/// (1) optimistically create shadow decls when they're not hidden
3330/// by existing declarations, or
3331/// (2) don't create any shadow decls (or at least don't make them
3332/// visible) until we've fully parsed/instantiated the class.
3333/// The problem with (1) is that we might have to retroactively remove
3334/// a shadow decl, which requires several O(n) operations because the
3335/// decl structures are (very reasonably) not designed for removal.
3336/// (2) avoids this but is very fiddly and phase-dependent.
3337void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3338 // Remove it from the DeclContext...
3339 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003340
John McCall9f54ad42009-12-10 09:41:52 +00003341 // ...and the scope, if applicable...
3342 if (S) {
3343 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3344 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003345 }
3346
John McCall9f54ad42009-12-10 09:41:52 +00003347 // ...and the using decl.
3348 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3349
3350 // TODO: complain somehow if Shadow was used. It shouldn't
3351 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003352}
3353
John McCall7ba107a2009-11-18 02:36:19 +00003354/// Builds a using declaration.
3355///
3356/// \param IsInstantiation - Whether this call arises from an
3357/// instantiation of an unresolved using declaration. We treat
3358/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003359NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3360 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003361 const CXXScopeSpec &SS,
3362 SourceLocation IdentLoc,
3363 DeclarationName Name,
3364 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003365 bool IsInstantiation,
3366 bool IsTypeName,
3367 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003368 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3369 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003370
Anders Carlsson550b14b2009-08-28 05:49:21 +00003371 // FIXME: We ignore attributes for now.
3372 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003374 if (SS.isEmpty()) {
3375 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003376 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003377 }
Mike Stump1eb44332009-09-09 15:08:12 +00003378
John McCall9f54ad42009-12-10 09:41:52 +00003379 // Do the redeclaration lookup in the current scope.
3380 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3381 ForRedeclaration);
3382 Previous.setHideTags(false);
3383 if (S) {
3384 LookupName(Previous, S);
3385
3386 // It is really dumb that we have to do this.
3387 LookupResult::Filter F = Previous.makeFilter();
3388 while (F.hasNext()) {
3389 NamedDecl *D = F.next();
3390 if (!isDeclInScope(D, CurContext, S))
3391 F.erase();
3392 }
3393 F.done();
3394 } else {
3395 assert(IsInstantiation && "no scope in non-instantiation");
3396 assert(CurContext->isRecord() && "scope not record in instantiation");
3397 LookupQualifiedName(Previous, CurContext);
3398 }
3399
Mike Stump1eb44332009-09-09 15:08:12 +00003400 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003401 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3402
John McCall9f54ad42009-12-10 09:41:52 +00003403 // Check for invalid redeclarations.
3404 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3405 return 0;
3406
3407 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003408 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3409 return 0;
3410
John McCallaf8e6ed2009-11-12 03:15:40 +00003411 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003412 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003413 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003414 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003415 // FIXME: not all declaration name kinds are legal here
3416 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3417 UsingLoc, TypenameLoc,
3418 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003419 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003420 } else {
3421 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3422 UsingLoc, SS.getRange(), NNS,
3423 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003424 }
John McCalled976492009-12-04 22:46:56 +00003425 } else {
3426 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3427 SS.getRange(), UsingLoc, NNS, Name,
3428 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003429 }
John McCalled976492009-12-04 22:46:56 +00003430 D->setAccess(AS);
3431 CurContext->addDecl(D);
3432
3433 if (!LookupContext) return D;
3434 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003435
John McCall604e7f12009-12-08 07:46:18 +00003436 if (RequireCompleteDeclContext(SS)) {
3437 UD->setInvalidDecl();
3438 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003439 }
3440
John McCall604e7f12009-12-08 07:46:18 +00003441 // Look up the target name.
3442
John McCalla24dc2e2009-11-17 02:14:36 +00003443 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003444
John McCall604e7f12009-12-08 07:46:18 +00003445 // Unlike most lookups, we don't always want to hide tag
3446 // declarations: tag names are visible through the using declaration
3447 // even if hidden by ordinary names, *except* in a dependent context
3448 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003449 if (!IsInstantiation)
3450 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003451
John McCalla24dc2e2009-11-17 02:14:36 +00003452 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003453
John McCallf36e02d2009-10-09 21:13:30 +00003454 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003455 Diag(IdentLoc, diag::err_no_member)
3456 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003457 UD->setInvalidDecl();
3458 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003459 }
3460
John McCalled976492009-12-04 22:46:56 +00003461 if (R.isAmbiguous()) {
3462 UD->setInvalidDecl();
3463 return UD;
3464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
John McCall7ba107a2009-11-18 02:36:19 +00003466 if (IsTypeName) {
3467 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003468 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003469 Diag(IdentLoc, diag::err_using_typename_non_type);
3470 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3471 Diag((*I)->getUnderlyingDecl()->getLocation(),
3472 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003473 UD->setInvalidDecl();
3474 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003475 }
3476 } else {
3477 // If we asked for a non-typename and we got a type, error out,
3478 // but only if this is an instantiation of an unresolved using
3479 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003480 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003481 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3482 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003483 UD->setInvalidDecl();
3484 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003485 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003486 }
3487
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003488 // C++0x N2914 [namespace.udecl]p6:
3489 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003490 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003491 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3492 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003493 UD->setInvalidDecl();
3494 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003495 }
Mike Stump1eb44332009-09-09 15:08:12 +00003496
John McCall9f54ad42009-12-10 09:41:52 +00003497 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3498 if (!CheckUsingShadowDecl(UD, *I, Previous))
3499 BuildUsingShadowDecl(S, UD, *I);
3500 }
John McCall9488ea12009-11-17 05:59:44 +00003501
3502 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003503}
3504
John McCall9f54ad42009-12-10 09:41:52 +00003505/// Checks that the given using declaration is not an invalid
3506/// redeclaration. Note that this is checking only for the using decl
3507/// itself, not for any ill-formedness among the UsingShadowDecls.
3508bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3509 bool isTypeName,
3510 const CXXScopeSpec &SS,
3511 SourceLocation NameLoc,
3512 const LookupResult &Prev) {
3513 // C++03 [namespace.udecl]p8:
3514 // C++0x [namespace.udecl]p10:
3515 // A using-declaration is a declaration and can therefore be used
3516 // repeatedly where (and only where) multiple declarations are
3517 // allowed.
3518 // That's only in file contexts.
3519 if (CurContext->getLookupContext()->isFileContext())
3520 return false;
3521
3522 NestedNameSpecifier *Qual
3523 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3524
3525 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3526 NamedDecl *D = *I;
3527
3528 bool DTypename;
3529 NestedNameSpecifier *DQual;
3530 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3531 DTypename = UD->isTypeName();
3532 DQual = UD->getTargetNestedNameDecl();
3533 } else if (UnresolvedUsingValueDecl *UD
3534 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3535 DTypename = false;
3536 DQual = UD->getTargetNestedNameSpecifier();
3537 } else if (UnresolvedUsingTypenameDecl *UD
3538 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3539 DTypename = true;
3540 DQual = UD->getTargetNestedNameSpecifier();
3541 } else continue;
3542
3543 // using decls differ if one says 'typename' and the other doesn't.
3544 // FIXME: non-dependent using decls?
3545 if (isTypeName != DTypename) continue;
3546
3547 // using decls differ if they name different scopes (but note that
3548 // template instantiation can cause this check to trigger when it
3549 // didn't before instantiation).
3550 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3551 Context.getCanonicalNestedNameSpecifier(DQual))
3552 continue;
3553
3554 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003555 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003556 return true;
3557 }
3558
3559 return false;
3560}
3561
John McCall604e7f12009-12-08 07:46:18 +00003562
John McCalled976492009-12-04 22:46:56 +00003563/// Checks that the given nested-name qualifier used in a using decl
3564/// in the current context is appropriately related to the current
3565/// scope. If an error is found, diagnoses it and returns true.
3566bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3567 const CXXScopeSpec &SS,
3568 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003569 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003570
John McCall604e7f12009-12-08 07:46:18 +00003571 if (!CurContext->isRecord()) {
3572 // C++03 [namespace.udecl]p3:
3573 // C++0x [namespace.udecl]p8:
3574 // A using-declaration for a class member shall be a member-declaration.
3575
3576 // If we weren't able to compute a valid scope, it must be a
3577 // dependent class scope.
3578 if (!NamedContext || NamedContext->isRecord()) {
3579 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3580 << SS.getRange();
3581 return true;
3582 }
3583
3584 // Otherwise, everything is known to be fine.
3585 return false;
3586 }
3587
3588 // The current scope is a record.
3589
3590 // If the named context is dependent, we can't decide much.
3591 if (!NamedContext) {
3592 // FIXME: in C++0x, we can diagnose if we can prove that the
3593 // nested-name-specifier does not refer to a base class, which is
3594 // still possible in some cases.
3595
3596 // Otherwise we have to conservatively report that things might be
3597 // okay.
3598 return false;
3599 }
3600
3601 if (!NamedContext->isRecord()) {
3602 // Ideally this would point at the last name in the specifier,
3603 // but we don't have that level of source info.
3604 Diag(SS.getRange().getBegin(),
3605 diag::err_using_decl_nested_name_specifier_is_not_class)
3606 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3607 return true;
3608 }
3609
3610 if (getLangOptions().CPlusPlus0x) {
3611 // C++0x [namespace.udecl]p3:
3612 // In a using-declaration used as a member-declaration, the
3613 // nested-name-specifier shall name a base class of the class
3614 // being defined.
3615
3616 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3617 cast<CXXRecordDecl>(NamedContext))) {
3618 if (CurContext == NamedContext) {
3619 Diag(NameLoc,
3620 diag::err_using_decl_nested_name_specifier_is_current_class)
3621 << SS.getRange();
3622 return true;
3623 }
3624
3625 Diag(SS.getRange().getBegin(),
3626 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3627 << (NestedNameSpecifier*) SS.getScopeRep()
3628 << cast<CXXRecordDecl>(CurContext)
3629 << SS.getRange();
3630 return true;
3631 }
3632
3633 return false;
3634 }
3635
3636 // C++03 [namespace.udecl]p4:
3637 // A using-declaration used as a member-declaration shall refer
3638 // to a member of a base class of the class being defined [etc.].
3639
3640 // Salient point: SS doesn't have to name a base class as long as
3641 // lookup only finds members from base classes. Therefore we can
3642 // diagnose here only if we can prove that that can't happen,
3643 // i.e. if the class hierarchies provably don't intersect.
3644
3645 // TODO: it would be nice if "definitely valid" results were cached
3646 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3647 // need to be repeated.
3648
3649 struct UserData {
3650 llvm::DenseSet<const CXXRecordDecl*> Bases;
3651
3652 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3653 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3654 Data->Bases.insert(Base);
3655 return true;
3656 }
3657
3658 bool hasDependentBases(const CXXRecordDecl *Class) {
3659 return !Class->forallBases(collect, this);
3660 }
3661
3662 /// Returns true if the base is dependent or is one of the
3663 /// accumulated base classes.
3664 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3665 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3666 return !Data->Bases.count(Base);
3667 }
3668
3669 bool mightShareBases(const CXXRecordDecl *Class) {
3670 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3671 }
3672 };
3673
3674 UserData Data;
3675
3676 // Returns false if we find a dependent base.
3677 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3678 return false;
3679
3680 // Returns false if the class has a dependent base or if it or one
3681 // of its bases is present in the base set of the current context.
3682 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3683 return false;
3684
3685 Diag(SS.getRange().getBegin(),
3686 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3687 << (NestedNameSpecifier*) SS.getScopeRep()
3688 << cast<CXXRecordDecl>(CurContext)
3689 << SS.getRange();
3690
3691 return true;
John McCalled976492009-12-04 22:46:56 +00003692}
3693
Mike Stump1eb44332009-09-09 15:08:12 +00003694Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003695 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003696 SourceLocation AliasLoc,
3697 IdentifierInfo *Alias,
3698 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003699 SourceLocation IdentLoc,
3700 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Anders Carlsson81c85c42009-03-28 23:53:49 +00003702 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003703 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3704 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003705
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003706 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003707 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003708 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003709 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003710 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003711 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003712 if (!R.isAmbiguous() && !R.empty() &&
3713 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003714 return DeclPtrTy();
3715 }
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003717 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3718 diag::err_redefinition_different_kind;
3719 Diag(AliasLoc, DiagID) << Alias;
3720 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003721 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003722 }
3723
John McCalla24dc2e2009-11-17 02:14:36 +00003724 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003725 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003726
John McCallf36e02d2009-10-09 21:13:30 +00003727 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003728 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003729 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003730 }
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003732 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003733 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3734 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003735 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003736 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003737
John McCall3dbd3d52010-02-16 06:53:13 +00003738 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00003739 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003740}
3741
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003742void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3743 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003744 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3745 !Constructor->isUsed()) &&
3746 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Eli Friedman80c30da2009-11-09 19:20:36 +00003748 CXXRecordDecl *ClassDecl
3749 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3750 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003751
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003752 DeclContext *PreviousContext = CurContext;
3753 CurContext = Constructor;
3754 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003755 Diag(CurrentLocation, diag::note_member_synthesized_at)
3756 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003757 Constructor->setInvalidDecl();
3758 } else {
3759 Constructor->setUsed();
3760 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003761 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003762}
3763
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003764void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003765 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003766 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3767 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003768 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003769 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003770
3771 DeclContext *PreviousContext = CurContext;
3772 CurContext = Destructor;
3773
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003774 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003775 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003776 // implicitly defined, all the implicitly-declared default destructors
3777 // for its base class and its non-static data members shall have been
3778 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3780 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003781 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003782 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003783 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003784 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003785 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3786 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3787 else
Mike Stump1eb44332009-09-09 15:08:12 +00003788 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003789 "DefineImplicitDestructor - missing dtor in a base class");
3790 }
3791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003793 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3794 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003795 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3796 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3797 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003798 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003799 CXXRecordDecl *FieldClassDecl
3800 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3801 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003802 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003803 const_cast<CXXDestructorDecl*>(
3804 FieldClassDecl->getDestructor(Context)))
3805 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3806 else
Mike Stump1eb44332009-09-09 15:08:12 +00003807 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003808 "DefineImplicitDestructor - missing dtor in class of a data member");
3809 }
3810 }
3811 }
Anders Carlsson37909802009-11-30 21:24:50 +00003812
3813 // FIXME: If CheckDestructor fails, we should emit a note about where the
3814 // implicit destructor was needed.
3815 if (CheckDestructor(Destructor)) {
3816 Diag(CurrentLocation, diag::note_member_synthesized_at)
3817 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3818
3819 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003820 CurContext = PreviousContext;
3821
Anders Carlsson37909802009-11-30 21:24:50 +00003822 return;
3823 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003824 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003825
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003826 Destructor->setUsed();
3827}
3828
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003829void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3830 CXXMethodDecl *MethodDecl) {
3831 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3832 MethodDecl->getOverloadedOperator() == OO_Equal &&
3833 !MethodDecl->isUsed()) &&
3834 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003836 CXXRecordDecl *ClassDecl
3837 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003839 DeclContext *PreviousContext = CurContext;
3840 CurContext = MethodDecl;
3841
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003842 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003843 // Before the implicitly-declared copy assignment operator for a class is
3844 // implicitly defined, all implicitly-declared copy assignment operators
3845 // for its direct base classes and its nonstatic data members shall have
3846 // been implicitly defined.
3847 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3849 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003850 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003852 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003853 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3854 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003855 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3856 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003857 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3858 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003859 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3860 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3861 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003862 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003863 CXXRecordDecl *FieldClassDecl
3864 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003865 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003866 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3867 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003868 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003869 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003870 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003871 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3872 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003873 Diag(CurrentLocation, diag::note_first_required_here);
3874 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003875 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003876 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003877 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3878 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003879 Diag(CurrentLocation, diag::note_first_required_here);
3880 err = true;
3881 }
3882 }
3883 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003884 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003885
3886 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003887}
3888
3889CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003890Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3891 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003892 CXXRecordDecl *ClassDecl) {
3893 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3894 QualType RHSType(LHSType);
3895 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003896 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003897 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003898 RHSType = Context.getCVRQualifiedType(RHSType,
3899 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003900 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003901 LHSType,
3902 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003903 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003904 RHSType,
3905 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003906 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003907 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003908 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003909 CandidateSet);
3910 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003911 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003912 return cast<CXXMethodDecl>(Best->Function);
3913 assert(false &&
3914 "getAssignOperatorMethod - copy assignment operator method not found");
3915 return 0;
3916}
3917
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003918void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3919 CXXConstructorDecl *CopyConstructor,
3920 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003921 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003922 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003923 !CopyConstructor->isUsed()) &&
3924 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003926 CXXRecordDecl *ClassDecl
3927 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3928 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003929
3930 DeclContext *PreviousContext = CurContext;
3931 CurContext = CopyConstructor;
3932
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003933 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003934 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003935 // implicitly defined, all the implicitly-declared copy constructors
3936 // for its base class and its non-static data members shall have been
3937 // implicitly defined.
3938 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3939 Base != ClassDecl->bases_end(); ++Base) {
3940 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003941 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003942 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003943 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003944 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003945 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003946 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3947 FieldEnd = ClassDecl->field_end();
3948 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003949 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3950 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3951 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003952 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003953 CXXRecordDecl *FieldClassDecl
3954 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003955 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003956 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003957 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003958 }
3959 }
3960 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003961
3962 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003963}
3964
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003965Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003966Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003967 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003968 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003969 bool RequiresZeroInit,
3970 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003971 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Douglas Gregor39da0b82009-09-09 23:08:42 +00003973 // C++ [class.copy]p15:
3974 // Whenever a temporary class object is copied using a copy constructor, and
3975 // this object and the copy have the same cv-unqualified type, an
3976 // implementation is permitted to treat the original and the copy as two
3977 // different ways of referring to the same object and not perform a copy at
3978 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003979
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003980 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003981 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003982 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003983 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3984 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3985 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003986 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3987 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003988 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3989 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3991 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3992 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003993
3994 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3995 Elidable = !CE->getCallReturnType()->isReferenceType();
3996 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003997 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003998 else if (isa<CXXConstructExpr>(E))
3999 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004000 }
Mike Stump1eb44332009-09-09 15:08:12 +00004001
4002 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004003 Elidable, move(ExprArgs), RequiresZeroInit,
4004 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004005}
4006
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004007/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4008/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004009Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004010Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4011 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004012 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004013 bool RequiresZeroInit,
4014 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004015 unsigned NumExprs = ExprArgs.size();
4016 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregor7edfb692009-11-23 12:27:39 +00004018 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004019 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004020 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004021 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004022}
4023
Mike Stump1eb44332009-09-09 15:08:12 +00004024bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004025 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004026 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004027 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004028 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004029 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004030 if (TempResult.isInvalid())
4031 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004033 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004034 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004035 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004036 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Anders Carlssonfe2de492009-08-25 05:18:00 +00004038 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004039}
4040
John McCall68c6c9a2010-02-02 09:10:11 +00004041void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4042 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004043 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4044 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004045 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4046 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004047 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004048 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004049}
4050
Mike Stump1eb44332009-09-09 15:08:12 +00004051/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004052/// ActOnDeclarator, when a C++ direct initializer is present.
4053/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004054void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4055 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004056 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004057 SourceLocation *CommaLocs,
4058 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004059 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004060 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004061
4062 // If there is no declaration, there was an error parsing it. Just ignore
4063 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004064 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004065 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004067 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4068 if (!VDecl) {
4069 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4070 RealDecl->setInvalidDecl();
4071 return;
4072 }
4073
Douglas Gregor83ddad32009-08-26 21:14:46 +00004074 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004075 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004076 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4077 //
4078 // Clients that want to distinguish between the two forms, can check for
4079 // direct initializer using VarDecl::hasCXXDirectInitializer().
4080 // A major benefit is that clients that don't particularly care about which
4081 // exactly form was it (like the CodeGen) can handle both cases without
4082 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004083
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004084 // C++ 8.5p11:
4085 // The form of initialization (using parentheses or '=') is generally
4086 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004087 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004088 QualType DeclInitType = VDecl->getType();
4089 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004090 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004091
Douglas Gregor4dffad62010-02-11 22:55:30 +00004092 if (!VDecl->getType()->isDependentType() &&
4093 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004094 diag::err_typecheck_decl_incomplete_type)) {
4095 VDecl->setInvalidDecl();
4096 return;
4097 }
4098
Douglas Gregor90f93822009-12-22 22:17:25 +00004099 // The variable can not have an abstract class type.
4100 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4101 diag::err_abstract_type_in_decl,
4102 AbstractVariableType))
4103 VDecl->setInvalidDecl();
4104
Sebastian Redl31310a22010-02-01 20:16:42 +00004105 const VarDecl *Def;
4106 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004107 Diag(VDecl->getLocation(), diag::err_redefinition)
4108 << VDecl->getDeclName();
4109 Diag(Def->getLocation(), diag::note_previous_definition);
4110 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004111 return;
4112 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004113
4114 // If either the declaration has a dependent type or if any of the
4115 // expressions is type-dependent, we represent the initialization
4116 // via a ParenListExpr for later use during template instantiation.
4117 if (VDecl->getType()->isDependentType() ||
4118 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4119 // Let clients know that initialization was done with a direct initializer.
4120 VDecl->setCXXDirectInitializer(true);
4121
4122 // Store the initialization expressions as a ParenListExpr.
4123 unsigned NumExprs = Exprs.size();
4124 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4125 (Expr **)Exprs.release(),
4126 NumExprs, RParenLoc));
4127 return;
4128 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004129
4130 // Capture the variable that is being initialized and the style of
4131 // initialization.
4132 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4133
4134 // FIXME: Poor source location information.
4135 InitializationKind Kind
4136 = InitializationKind::CreateDirect(VDecl->getLocation(),
4137 LParenLoc, RParenLoc);
4138
4139 InitializationSequence InitSeq(*this, Entity, Kind,
4140 (Expr**)Exprs.get(), Exprs.size());
4141 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4142 if (Result.isInvalid()) {
4143 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004144 return;
4145 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004146
4147 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004148 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004149 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004150
John McCall68c6c9a2010-02-02 09:10:11 +00004151 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4152 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004153}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004154
Douglas Gregor19aeac62009-11-14 03:27:21 +00004155/// \brief Add the applicable constructor candidates for an initialization
4156/// by constructor.
4157static void AddConstructorInitializationCandidates(Sema &SemaRef,
4158 QualType ClassType,
4159 Expr **Args,
4160 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004161 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004162 OverloadCandidateSet &CandidateSet) {
4163 // C++ [dcl.init]p14:
4164 // If the initialization is direct-initialization, or if it is
4165 // copy-initialization where the cv-unqualified version of the
4166 // source type is the same class as, or a derived class of, the
4167 // class of the destination, constructors are considered. The
4168 // applicable constructors are enumerated (13.3.1.3), and the
4169 // best one is chosen through overload resolution (13.3). The
4170 // constructor so selected is called to initialize the object,
4171 // with the initializer expression(s) as its argument(s). If no
4172 // constructor applies, or the overload resolution is ambiguous,
4173 // the initialization is ill-formed.
4174 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4175 assert(ClassRec && "Can only initialize a class type here");
4176
4177 // FIXME: When we decide not to synthesize the implicitly-declared
4178 // constructors, we'll need to make them appear here.
4179
4180 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4181 DeclarationName ConstructorName
4182 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4183 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4184 DeclContext::lookup_const_iterator Con, ConEnd;
4185 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4186 Con != ConEnd; ++Con) {
4187 // Find the constructor (which may be a template).
4188 CXXConstructorDecl *Constructor = 0;
4189 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4190 if (ConstructorTmpl)
4191 Constructor
4192 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4193 else
4194 Constructor = cast<CXXConstructorDecl>(*Con);
4195
Douglas Gregor20093b42009-12-09 23:02:17 +00004196 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4197 (Kind.getKind() == InitializationKind::IK_Value) ||
4198 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004199 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004200 ((Kind.getKind() == InitializationKind::IK_Default) &&
4201 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004202 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004203 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004204 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004205 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004206 Args, NumArgs, CandidateSet);
4207 else
John McCall86820f52010-01-26 01:37:31 +00004208 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4209 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004210 }
4211 }
4212}
4213
4214/// \brief Attempt to perform initialization by constructor
4215/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4216/// copy-initialization.
4217///
4218/// This routine determines whether initialization by constructor is possible,
4219/// but it does not emit any diagnostics in the case where the initialization
4220/// is ill-formed.
4221///
4222/// \param ClassType the type of the object being initialized, which must have
4223/// class type.
4224///
4225/// \param Args the arguments provided to initialize the object
4226///
4227/// \param NumArgs the number of arguments provided to initialize the object
4228///
4229/// \param Kind the type of initialization being performed
4230///
4231/// \returns the constructor used to initialize the object, if successful.
4232/// Otherwise, emits a diagnostic and returns NULL.
4233CXXConstructorDecl *
4234Sema::TryInitializationByConstructor(QualType ClassType,
4235 Expr **Args, unsigned NumArgs,
4236 SourceLocation Loc,
4237 InitializationKind Kind) {
4238 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004239 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004240 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4241 CandidateSet);
4242
4243 // Determine whether we found a constructor we can use.
4244 OverloadCandidateSet::iterator Best;
4245 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4246 case OR_Success:
4247 case OR_Deleted:
4248 // We found a constructor. Return it.
4249 return cast<CXXConstructorDecl>(Best->Function);
4250
4251 case OR_No_Viable_Function:
4252 case OR_Ambiguous:
4253 // Overload resolution failed. Return nothing.
4254 return 0;
4255 }
4256
4257 // Silence GCC warning
4258 return 0;
4259}
4260
Douglas Gregor39da0b82009-09-09 23:08:42 +00004261/// \brief Given a constructor and the set of arguments provided for the
4262/// constructor, convert the arguments and add any required default arguments
4263/// to form a proper call to this constructor.
4264///
4265/// \returns true if an error occurred, false otherwise.
4266bool
4267Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4268 MultiExprArg ArgsPtr,
4269 SourceLocation Loc,
4270 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4271 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4272 unsigned NumArgs = ArgsPtr.size();
4273 Expr **Args = (Expr **)ArgsPtr.get();
4274
4275 const FunctionProtoType *Proto
4276 = Constructor->getType()->getAs<FunctionProtoType>();
4277 assert(Proto && "Constructor without a prototype?");
4278 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004279
4280 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004281 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004282 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004283 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004284 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004285
4286 VariadicCallType CallType =
4287 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4288 llvm::SmallVector<Expr *, 8> AllArgs;
4289 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4290 Proto, 0, Args, NumArgs, AllArgs,
4291 CallType);
4292 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4293 ConvertedArgs.push_back(AllArgs[i]);
4294 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004295}
4296
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004297/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4298/// determine whether they are reference-related,
4299/// reference-compatible, reference-compatible with added
4300/// qualification, or incompatible, for use in C++ initialization by
4301/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4302/// type, and the first type (T1) is the pointee type of the reference
4303/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004304Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004305Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004306 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004307 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004308 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004309 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004310 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004311
Douglas Gregor393896f2009-11-05 13:06:35 +00004312 QualType T1 = Context.getCanonicalType(OrigT1);
4313 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004314 Qualifiers T1Quals, T2Quals;
4315 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4316 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004317
4318 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004319 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004320 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004321 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004322 if (UnqualT1 == UnqualT2)
4323 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004324 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4325 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4326 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004327 DerivedToBase = true;
4328 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004329 return Ref_Incompatible;
4330
4331 // At this point, we know that T1 and T2 are reference-related (at
4332 // least).
4333
Chandler Carruth28e318c2009-12-29 07:16:59 +00004334 // If the type is an array type, promote the element qualifiers to the type
4335 // for comparison.
4336 if (isa<ArrayType>(T1) && T1Quals)
4337 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4338 if (isa<ArrayType>(T2) && T2Quals)
4339 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4340
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004341 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004342 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004343 // reference-related to T2 and cv1 is the same cv-qualification
4344 // as, or greater cv-qualification than, cv2. For purposes of
4345 // overload resolution, cases for which cv1 is greater
4346 // cv-qualification than cv2 are identified as
4347 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004348 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004349 return Ref_Compatible;
4350 else if (T1.isMoreQualifiedThan(T2))
4351 return Ref_Compatible_With_Added_Qualification;
4352 else
4353 return Ref_Related;
4354}
4355
4356/// CheckReferenceInit - Check the initialization of a reference
4357/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4358/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004359/// list), and DeclType is the type of the declaration. When ICS is
4360/// non-null, this routine will compute the implicit conversion
4361/// sequence according to C++ [over.ics.ref] and will not produce any
4362/// diagnostics; when ICS is null, it will emit diagnostics when any
4363/// errors are found. Either way, a return value of true indicates
4364/// that there was a failure, a return value of false indicates that
4365/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004366///
4367/// When @p SuppressUserConversions, user-defined conversions are
4368/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004369/// When @p AllowExplicit, we also permit explicit user-defined
4370/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004371/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004372/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4373/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004374bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004375Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004376 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004377 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004378 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004379 ImplicitConversionSequence *ICS,
4380 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004381 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4382
Ted Kremenek6217b802009-07-29 21:53:49 +00004383 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004384 QualType T2 = Init->getType();
4385
Douglas Gregor904eed32008-11-10 20:40:00 +00004386 // If the initializer is the address of an overloaded function, try
4387 // to resolve the overloaded function. If all goes well, T2 is the
4388 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004389 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004390 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004391 ICS != 0);
4392 if (Fn) {
4393 // Since we're performing this reference-initialization for
4394 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004395 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004396 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004397 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004398
Anders Carlsson96ad5332009-10-21 17:16:23 +00004399 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004400 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004401
4402 T2 = Fn->getType();
4403 }
4404 }
4405
Douglas Gregor15da57e2008-10-29 02:00:59 +00004406 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004407 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004408 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004409 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4410 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004411 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004412 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004413
4414 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004415 if (ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00004416 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCalladbb8f82010-01-13 09:16:55 +00004417 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004418
4419 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004420 // A reference to type "cv1 T1" is initialized by an expression
4421 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004422
4423 // -- If the initializer expression
4424
Sebastian Redla9845802009-03-29 15:27:50 +00004425 // Rvalue references cannot bind to lvalues (N2812).
4426 // There is absolutely no situation where they can. In particular, note that
4427 // this is ill-formed, even if B has a user-defined conversion to A&&:
4428 // B b;
4429 // A&& r = b;
4430 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4431 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004432 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004433 << Init->getSourceRange();
4434 return true;
4435 }
4436
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004437 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004438 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4439 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004440 //
4441 // Note that the bit-field check is skipped if we are just computing
4442 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004443 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004444 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004445 BindsDirectly = true;
4446
Douglas Gregor15da57e2008-10-29 02:00:59 +00004447 if (ICS) {
4448 // C++ [over.ics.ref]p1:
4449 // When a parameter of reference type binds directly (8.5.3)
4450 // to an argument expression, the implicit conversion sequence
4451 // is the identity conversion, unless the argument expression
4452 // has a type that is a derived class of the parameter type,
4453 // in which case the implicit conversion sequence is a
4454 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004455 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004456 ICS->Standard.First = ICK_Identity;
4457 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4458 ICS->Standard.Third = ICK_Identity;
4459 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004460 ICS->Standard.setToType(0, T2);
4461 ICS->Standard.setToType(1, T1);
4462 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004463 ICS->Standard.ReferenceBinding = true;
4464 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004465 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004466 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004467
4468 // Nothing more to do: the inaccessibility/ambiguity check for
4469 // derived-to-base conversions is suppressed when we're
4470 // computing the implicit conversion sequence (C++
4471 // [over.best.ics]p2).
4472 return false;
4473 } else {
4474 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004475 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4476 if (DerivedToBase)
4477 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004478 else if(CheckExceptionSpecCompatibility(Init, T1))
4479 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004480 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004481 }
4482 }
4483
4484 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004485 // implicitly converted to an lvalue of type "cv3 T3,"
4486 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004487 // 92) (this conversion is selected by enumerating the
4488 // applicable conversion functions (13.3.1.6) and choosing
4489 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004490 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004491 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004492 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004493 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004494
John McCall5769d612010-02-08 23:07:23 +00004495 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004496 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004497 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004498 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004499 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004500 NamedDecl *D = *I;
4501 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4502 if (isa<UsingShadowDecl>(D))
4503 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4504
Mike Stump1eb44332009-09-09 15:08:12 +00004505 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004506 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004507 CXXConversionDecl *Conv;
4508 if (ConvTemplate)
4509 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4510 else
John McCall701c89e2009-12-03 04:06:58 +00004511 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004512
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004513 // If the conversion function doesn't return a reference type,
4514 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004515 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004516 (AllowExplicit || !Conv->isExplicit())) {
4517 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004518 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004519 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004520 else
John McCall86820f52010-01-26 01:37:31 +00004521 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4522 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004523 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004524 }
4525
4526 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004527 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004528 case OR_Success:
Douglas Gregora1a9f032010-03-07 23:17:44 +00004529 // C++ [over.ics.ref]p1:
4530 //
4531 // [...] If the parameter binds directly to the result of
4532 // applying a conversion function to the argument
4533 // expression, the implicit conversion sequence is a
4534 // user-defined conversion sequence (13.3.3.1.2), with the
4535 // second standard conversion sequence either an identity
4536 // conversion or, if the conversion function returns an
4537 // entity of a type that is a derived class of the parameter
4538 // type, a derived-to-base Conversion.
4539 if (!Best->FinalConversion.DirectBinding)
4540 break;
4541
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004542 // This is a direct binding.
4543 BindsDirectly = true;
4544
4545 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004546 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004547 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4548 ICS->UserDefined.After = Best->FinalConversion;
4549 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004550 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004551 assert(ICS->UserDefined.After.ReferenceBinding &&
4552 ICS->UserDefined.After.DirectBinding &&
4553 "Expected a direct reference binding!");
4554 return false;
4555 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004556 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004557 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004558 CastExpr::CK_UserDefinedConversion,
4559 cast<CXXMethodDecl>(Best->Function),
4560 Owned(Init));
4561 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004562
4563 if (CheckExceptionSpecCompatibility(Init, T1))
4564 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004565 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4566 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004567 }
4568 break;
4569
4570 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004571 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004572 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004573 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4574 Cand != CandidateSet.end(); ++Cand)
4575 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004576 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004577 break;
4578 }
4579 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4580 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004581 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004582 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004584 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004585 case OR_Deleted:
4586 // There was no suitable conversion, or we found a deleted
4587 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004588 break;
4589 }
4590 }
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004592 if (BindsDirectly) {
4593 // C++ [dcl.init.ref]p4:
4594 // [...] In all cases where the reference-related or
4595 // reference-compatible relationship of two types is used to
4596 // establish the validity of a reference binding, and T1 is a
4597 // base class of T2, a program that necessitates such a binding
4598 // is ill-formed if T1 is an inaccessible (clause 11) or
4599 // ambiguous (10.2) base class of T2.
4600 //
4601 // Note that we only check this condition when we're allowed to
4602 // complain about errors, because we should not be checking for
4603 // ambiguity (or inaccessibility) unless the reference binding
4604 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004605 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004606 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004607 Init->getSourceRange(),
4608 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004609 else
4610 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004611 }
4612
4613 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004614 // type (i.e., cv1 shall be const), or the reference shall be an
4615 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004616 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004617 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004618 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004619 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004620 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004621 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004622 return true;
4623 }
4624
4625 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004626 // class type, and "cv1 T1" is reference-compatible with
4627 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004628 // following ways (the choice is implementation-defined):
4629 //
4630 // -- The reference is bound to the object represented by
4631 // the rvalue (see 3.10) or to a sub-object within that
4632 // object.
4633 //
Eli Friedman33a31382009-08-05 19:21:58 +00004634 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004635 // a constructor is called to copy the entire rvalue
4636 // object into the temporary. The reference is bound to
4637 // the temporary or to a sub-object within the
4638 // temporary.
4639 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004640 // The constructor that would be used to make the copy
4641 // shall be callable whether or not the copy is actually
4642 // done.
4643 //
Sebastian Redla9845802009-03-29 15:27:50 +00004644 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004645 // freedom, so we will always take the first option and never build
4646 // a temporary in this case. FIXME: We will, however, have to check
4647 // for the presence of a copy constructor in C++98/03 mode.
4648 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004649 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4650 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004651 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004652 ICS->Standard.First = ICK_Identity;
4653 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4654 ICS->Standard.Third = ICK_Identity;
4655 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004656 ICS->Standard.setToType(0, T2);
4657 ICS->Standard.setToType(1, T1);
4658 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004659 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004660 ICS->Standard.DirectBinding = false;
4661 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004662 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004663 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004664 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4665 if (DerivedToBase)
4666 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004667 else if(CheckExceptionSpecCompatibility(Init, T1))
4668 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004669 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004670 }
4671 return false;
4672 }
4673
Eli Friedman33a31382009-08-05 19:21:58 +00004674 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004675 // initialized from the initializer expression using the
4676 // rules for a non-reference copy initialization (8.5). The
4677 // reference is then bound to the temporary. If T1 is
4678 // reference-related to T2, cv1 must be the same
4679 // cv-qualification as, or greater cv-qualification than,
4680 // cv2; otherwise, the program is ill-formed.
4681 if (RefRelationship == Ref_Related) {
4682 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4683 // we would be reference-compatible or reference-compatible with
4684 // added qualification. But that wasn't the case, so the reference
4685 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004686 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004687 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004688 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004689 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004690 return true;
4691 }
4692
Douglas Gregor734d9862009-01-30 23:27:23 +00004693 // If at least one of the types is a class type, the types are not
4694 // related, and we aren't allowed any user conversions, the
4695 // reference binding fails. This case is important for breaking
4696 // recursion, since TryImplicitConversion below will attempt to
4697 // create a temporary through the use of a copy constructor.
4698 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4699 (T1->isRecordType() || T2->isRecordType())) {
4700 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004701 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004702 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004703 return true;
4704 }
4705
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004706 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004707 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004708 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004709 //
Sebastian Redla9845802009-03-29 15:27:50 +00004710 // When a parameter of reference type is not bound directly to
4711 // an argument expression, the conversion sequence is the one
4712 // required to convert the argument expression to the
4713 // underlying type of the reference according to
4714 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4715 // to copy-initializing a temporary of the underlying type with
4716 // the argument expression. Any difference in top-level
4717 // cv-qualification is subsumed by the initialization itself
4718 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004719 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4720 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004721 /*ForceRValue=*/false,
4722 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Sebastian Redla9845802009-03-29 15:27:50 +00004724 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004725 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004726 ICS->Standard.ReferenceBinding = true;
4727 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004728 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004729 ICS->UserDefined.After.ReferenceBinding = true;
4730 ICS->UserDefined.After.RRefBinding = isRValRef;
4731 }
John McCall1d318332010-01-12 00:44:57 +00004732 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004733 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004734 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004735 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004736 false, false,
4737 Conversions);
4738 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004739 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004740 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004741 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004742 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004743 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004744 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004745 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004746 }
4747 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004748 else {
4749 if (isRValRef)
4750 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4751 << Init->getSourceRange();
4752 else
4753 Diag(DeclLoc, diag::err_invalid_initialization)
4754 << DeclType << Init->getType() << Init->getSourceRange();
4755 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004756 }
4757 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004758 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004759}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004760
Anders Carlsson20d45d22009-12-12 00:32:00 +00004761static inline bool
4762CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4763 const FunctionDecl *FnDecl) {
4764 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4765 if (isa<NamespaceDecl>(DC)) {
4766 return SemaRef.Diag(FnDecl->getLocation(),
4767 diag::err_operator_new_delete_declared_in_namespace)
4768 << FnDecl->getDeclName();
4769 }
4770
4771 if (isa<TranslationUnitDecl>(DC) &&
4772 FnDecl->getStorageClass() == FunctionDecl::Static) {
4773 return SemaRef.Diag(FnDecl->getLocation(),
4774 diag::err_operator_new_delete_declared_static)
4775 << FnDecl->getDeclName();
4776 }
4777
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004778 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004779}
4780
Anders Carlsson156c78e2009-12-13 17:53:43 +00004781static inline bool
4782CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4783 CanQualType ExpectedResultType,
4784 CanQualType ExpectedFirstParamType,
4785 unsigned DependentParamTypeDiag,
4786 unsigned InvalidParamTypeDiag) {
4787 QualType ResultType =
4788 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4789
4790 // Check that the result type is not dependent.
4791 if (ResultType->isDependentType())
4792 return SemaRef.Diag(FnDecl->getLocation(),
4793 diag::err_operator_new_delete_dependent_result_type)
4794 << FnDecl->getDeclName() << ExpectedResultType;
4795
4796 // Check that the result type is what we expect.
4797 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4798 return SemaRef.Diag(FnDecl->getLocation(),
4799 diag::err_operator_new_delete_invalid_result_type)
4800 << FnDecl->getDeclName() << ExpectedResultType;
4801
4802 // A function template must have at least 2 parameters.
4803 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4804 return SemaRef.Diag(FnDecl->getLocation(),
4805 diag::err_operator_new_delete_template_too_few_parameters)
4806 << FnDecl->getDeclName();
4807
4808 // The function decl must have at least 1 parameter.
4809 if (FnDecl->getNumParams() == 0)
4810 return SemaRef.Diag(FnDecl->getLocation(),
4811 diag::err_operator_new_delete_too_few_parameters)
4812 << FnDecl->getDeclName();
4813
4814 // Check the the first parameter type is not dependent.
4815 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4816 if (FirstParamType->isDependentType())
4817 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4818 << FnDecl->getDeclName() << ExpectedFirstParamType;
4819
4820 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004821 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004822 ExpectedFirstParamType)
4823 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4824 << FnDecl->getDeclName() << ExpectedFirstParamType;
4825
4826 return false;
4827}
4828
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004829static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004830CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004831 // C++ [basic.stc.dynamic.allocation]p1:
4832 // A program is ill-formed if an allocation function is declared in a
4833 // namespace scope other than global scope or declared static in global
4834 // scope.
4835 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4836 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004837
4838 CanQualType SizeTy =
4839 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4840
4841 // C++ [basic.stc.dynamic.allocation]p1:
4842 // The return type shall be void*. The first parameter shall have type
4843 // std::size_t.
4844 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4845 SizeTy,
4846 diag::err_operator_new_dependent_param_type,
4847 diag::err_operator_new_param_type))
4848 return true;
4849
4850 // C++ [basic.stc.dynamic.allocation]p1:
4851 // The first parameter shall not have an associated default argument.
4852 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004853 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004854 diag::err_operator_new_default_arg)
4855 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4856
4857 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004858}
4859
4860static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004861CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4862 // C++ [basic.stc.dynamic.deallocation]p1:
4863 // A program is ill-formed if deallocation functions are declared in a
4864 // namespace scope other than global scope or declared static in global
4865 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004866 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4867 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004868
4869 // C++ [basic.stc.dynamic.deallocation]p2:
4870 // Each deallocation function shall return void and its first parameter
4871 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004872 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4873 SemaRef.Context.VoidPtrTy,
4874 diag::err_operator_delete_dependent_param_type,
4875 diag::err_operator_delete_param_type))
4876 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004877
Anders Carlsson46991d62009-12-12 00:16:02 +00004878 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4879 if (FirstParamType->isDependentType())
4880 return SemaRef.Diag(FnDecl->getLocation(),
4881 diag::err_operator_delete_dependent_param_type)
4882 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4883
4884 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4885 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004886 return SemaRef.Diag(FnDecl->getLocation(),
4887 diag::err_operator_delete_param_type)
4888 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004889
4890 return false;
4891}
4892
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004893/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4894/// of this overloaded operator is well-formed. If so, returns false;
4895/// otherwise, emits appropriate diagnostics and returns true.
4896bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004897 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004898 "Expected an overloaded operator declaration");
4899
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004900 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4901
Mike Stump1eb44332009-09-09 15:08:12 +00004902 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004903 // The allocation and deallocation functions, operator new,
4904 // operator new[], operator delete and operator delete[], are
4905 // described completely in 3.7.3. The attributes and restrictions
4906 // found in the rest of this subclause do not apply to them unless
4907 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004908 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004909 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004910
Anders Carlssona3ccda52009-12-12 00:26:23 +00004911 if (Op == OO_New || Op == OO_Array_New)
4912 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004913
4914 // C++ [over.oper]p6:
4915 // An operator function shall either be a non-static member
4916 // function or be a non-member function and have at least one
4917 // parameter whose type is a class, a reference to a class, an
4918 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004919 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4920 if (MethodDecl->isStatic())
4921 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004922 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004923 } else {
4924 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004925 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4926 ParamEnd = FnDecl->param_end();
4927 Param != ParamEnd; ++Param) {
4928 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004929 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4930 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004931 ClassOrEnumParam = true;
4932 break;
4933 }
4934 }
4935
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004936 if (!ClassOrEnumParam)
4937 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004938 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004939 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004940 }
4941
4942 // C++ [over.oper]p8:
4943 // An operator function cannot have default arguments (8.3.6),
4944 // except where explicitly stated below.
4945 //
Mike Stump1eb44332009-09-09 15:08:12 +00004946 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004947 // (C++ [over.call]p1).
4948 if (Op != OO_Call) {
4949 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4950 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004951 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004952 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004953 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004954 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004955 }
4956 }
4957
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004958 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4959 { false, false, false }
4960#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4961 , { Unary, Binary, MemberOnly }
4962#include "clang/Basic/OperatorKinds.def"
4963 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004964
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004965 bool CanBeUnaryOperator = OperatorUses[Op][0];
4966 bool CanBeBinaryOperator = OperatorUses[Op][1];
4967 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004968
4969 // C++ [over.oper]p8:
4970 // [...] Operator functions cannot have more or fewer parameters
4971 // than the number required for the corresponding operator, as
4972 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004973 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004974 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004975 if (Op != OO_Call &&
4976 ((NumParams == 1 && !CanBeUnaryOperator) ||
4977 (NumParams == 2 && !CanBeBinaryOperator) ||
4978 (NumParams < 1) || (NumParams > 2))) {
4979 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004980 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004981 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004982 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004983 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004984 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004985 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004986 assert(CanBeBinaryOperator &&
4987 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004988 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004989 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004990
Chris Lattner416e46f2008-11-21 07:57:12 +00004991 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004992 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004993 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004994
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004995 // Overloaded operators other than operator() cannot be variadic.
4996 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004997 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004998 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004999 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005000 }
5001
5002 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005003 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5004 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005005 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005006 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005007 }
5008
5009 // C++ [over.inc]p1:
5010 // The user-defined function called operator++ implements the
5011 // prefix and postfix ++ operator. If this function is a member
5012 // function with no parameters, or a non-member function with one
5013 // parameter of class or enumeration type, it defines the prefix
5014 // increment operator ++ for objects of that type. If the function
5015 // is a member function with one parameter (which shall be of type
5016 // int) or a non-member function with two parameters (the second
5017 // of which shall be of type int), it defines the postfix
5018 // increment operator ++ for objects of that type.
5019 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5020 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5021 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005022 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005023 ParamIsInt = BT->getKind() == BuiltinType::Int;
5024
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005025 if (!ParamIsInt)
5026 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005027 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005028 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005029 }
5030
Sebastian Redl64b45f72009-01-05 20:52:13 +00005031 // Notify the class if it got an assignment operator.
5032 if (Op == OO_Equal) {
5033 // Would have returned earlier otherwise.
5034 assert(isa<CXXMethodDecl>(FnDecl) &&
5035 "Overloaded = not member, but not filtered.");
5036 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5037 Method->getParent()->addedAssignmentOperator(Context, Method);
5038 }
5039
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005040 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005041}
Chris Lattner5a003a42008-12-17 07:09:26 +00005042
Sean Hunta6c058d2010-01-13 09:01:02 +00005043/// CheckLiteralOperatorDeclaration - Check whether the declaration
5044/// of this literal operator function is well-formed. If so, returns
5045/// false; otherwise, emits appropriate diagnostics and returns true.
5046bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5047 DeclContext *DC = FnDecl->getDeclContext();
5048 Decl::Kind Kind = DC->getDeclKind();
5049 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5050 Kind != Decl::LinkageSpec) {
5051 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5052 << FnDecl->getDeclName();
5053 return true;
5054 }
5055
5056 bool Valid = false;
5057
5058 // FIXME: Check for the one valid template signature
5059 // template <char...> type operator "" name();
5060
5061 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5062 // Check the first parameter
5063 QualType T = (*Param)->getType();
5064
5065 // unsigned long long int and long double are allowed, but only
5066 // alone.
5067 // We also allow any character type; their omission seems to be a bug
5068 // in n3000
5069 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5070 Context.hasSameType(T, Context.LongDoubleTy) ||
5071 Context.hasSameType(T, Context.CharTy) ||
5072 Context.hasSameType(T, Context.WCharTy) ||
5073 Context.hasSameType(T, Context.Char16Ty) ||
5074 Context.hasSameType(T, Context.Char32Ty)) {
5075 if (++Param == FnDecl->param_end())
5076 Valid = true;
5077 goto FinishedParams;
5078 }
5079
5080 // Otherwise it must be a pointer to const; let's strip those.
5081 const PointerType *PT = T->getAs<PointerType>();
5082 if (!PT)
5083 goto FinishedParams;
5084 T = PT->getPointeeType();
5085 if (!T.isConstQualified())
5086 goto FinishedParams;
5087 T = T.getUnqualifiedType();
5088
5089 // Move on to the second parameter;
5090 ++Param;
5091
5092 // If there is no second parameter, the first must be a const char *
5093 if (Param == FnDecl->param_end()) {
5094 if (Context.hasSameType(T, Context.CharTy))
5095 Valid = true;
5096 goto FinishedParams;
5097 }
5098
5099 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5100 // are allowed as the first parameter to a two-parameter function
5101 if (!(Context.hasSameType(T, Context.CharTy) ||
5102 Context.hasSameType(T, Context.WCharTy) ||
5103 Context.hasSameType(T, Context.Char16Ty) ||
5104 Context.hasSameType(T, Context.Char32Ty)))
5105 goto FinishedParams;
5106
5107 // The second and final parameter must be an std::size_t
5108 T = (*Param)->getType().getUnqualifiedType();
5109 if (Context.hasSameType(T, Context.getSizeType()) &&
5110 ++Param == FnDecl->param_end())
5111 Valid = true;
5112 }
5113
5114 // FIXME: This diagnostic is absolutely terrible.
5115FinishedParams:
5116 if (!Valid) {
5117 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5118 << FnDecl->getDeclName();
5119 return true;
5120 }
5121
5122 return false;
5123}
5124
Douglas Gregor074149e2009-01-05 19:45:36 +00005125/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5126/// linkage specification, including the language and (if present)
5127/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5128/// the location of the language string literal, which is provided
5129/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5130/// the '{' brace. Otherwise, this linkage specification does not
5131/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005132Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5133 SourceLocation ExternLoc,
5134 SourceLocation LangLoc,
5135 const char *Lang,
5136 unsigned StrSize,
5137 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005138 LinkageSpecDecl::LanguageIDs Language;
5139 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5140 Language = LinkageSpecDecl::lang_c;
5141 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5142 Language = LinkageSpecDecl::lang_cxx;
5143 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005144 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005145 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005146 }
Mike Stump1eb44332009-09-09 15:08:12 +00005147
Chris Lattnercc98eac2008-12-17 07:13:27 +00005148 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005149
Douglas Gregor074149e2009-01-05 19:45:36 +00005150 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005151 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005152 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005153 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005154 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005155 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005156}
5157
Douglas Gregor074149e2009-01-05 19:45:36 +00005158/// ActOnFinishLinkageSpecification - Completely the definition of
5159/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5160/// valid, it's the position of the closing '}' brace in a linkage
5161/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005162Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5163 DeclPtrTy LinkageSpec,
5164 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005165 if (LinkageSpec)
5166 PopDeclContext();
5167 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005168}
5169
Douglas Gregord308e622009-05-18 20:51:54 +00005170/// \brief Perform semantic analysis for the variable declaration that
5171/// occurs within a C++ catch clause, returning the newly-created
5172/// variable.
5173VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005174 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005175 IdentifierInfo *Name,
5176 SourceLocation Loc,
5177 SourceRange Range) {
5178 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005179
5180 // Arrays and functions decay.
5181 if (ExDeclType->isArrayType())
5182 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5183 else if (ExDeclType->isFunctionType())
5184 ExDeclType = Context.getPointerType(ExDeclType);
5185
5186 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5187 // The exception-declaration shall not denote a pointer or reference to an
5188 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005189 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005190 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005191 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005192 Invalid = true;
5193 }
Douglas Gregord308e622009-05-18 20:51:54 +00005194
Sebastian Redl4b07b292008-12-22 19:15:10 +00005195 QualType BaseType = ExDeclType;
5196 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005197 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005198 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005199 BaseType = Ptr->getPointeeType();
5200 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005201 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005202 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005203 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005204 BaseType = Ref->getPointeeType();
5205 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005206 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005207 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005208 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005209 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005210 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005211
Mike Stump1eb44332009-09-09 15:08:12 +00005212 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005213 RequireNonAbstractType(Loc, ExDeclType,
5214 diag::err_abstract_type_in_decl,
5215 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005216 Invalid = true;
5217
Mike Stump1eb44332009-09-09 15:08:12 +00005218 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005219 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005220
Douglas Gregor6d182892010-03-05 23:38:39 +00005221 if (!Invalid) {
5222 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5223 // C++ [except.handle]p16:
5224 // The object declared in an exception-declaration or, if the
5225 // exception-declaration does not specify a name, a temporary (12.2) is
5226 // copy-initialized (8.5) from the exception object. [...]
5227 // The object is destroyed when the handler exits, after the destruction
5228 // of any automatic objects initialized within the handler.
5229 //
5230 // We just pretend to initialize the object with itself, then make sure
5231 // it can be destroyed later.
5232 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5233 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5234 Loc, ExDeclType, 0);
5235 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5236 SourceLocation());
5237 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5238 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5239 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5240 if (Result.isInvalid())
5241 Invalid = true;
5242 else
5243 FinalizeVarWithDestructor(ExDecl, RecordTy);
5244 }
5245 }
5246
Douglas Gregord308e622009-05-18 20:51:54 +00005247 if (Invalid)
5248 ExDecl->setInvalidDecl();
5249
5250 return ExDecl;
5251}
5252
5253/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5254/// handler.
5255Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005256 TypeSourceInfo *TInfo = 0;
5257 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005258
5259 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005260 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005261 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005262 // The scope should be freshly made just for us. There is just no way
5263 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005264 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005265 if (PrevDecl->isTemplateParameter()) {
5266 // Maybe we will complain about the shadowed template parameter.
5267 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005268 }
5269 }
5270
Chris Lattnereaaebc72009-04-25 08:06:05 +00005271 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005272 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5273 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005274 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005275 }
5276
John McCalla93c9342009-12-07 02:54:59 +00005277 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005278 D.getIdentifier(),
5279 D.getIdentifierLoc(),
5280 D.getDeclSpec().getSourceRange());
5281
Chris Lattnereaaebc72009-04-25 08:06:05 +00005282 if (Invalid)
5283 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Sebastian Redl4b07b292008-12-22 19:15:10 +00005285 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005286 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005287 PushOnScopeChains(ExDecl, S);
5288 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005289 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005290
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005291 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005292 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005293}
Anders Carlssonfb311762009-03-14 00:25:26 +00005294
Mike Stump1eb44332009-09-09 15:08:12 +00005295Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005296 ExprArg assertexpr,
5297 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005298 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005299 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005300 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5301
Anders Carlssonc3082412009-03-14 00:33:21 +00005302 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5303 llvm::APSInt Value(32);
5304 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5305 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5306 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005307 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005308 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005309
Anders Carlssonc3082412009-03-14 00:33:21 +00005310 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005311 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005312 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005313 }
5314 }
Mike Stump1eb44332009-09-09 15:08:12 +00005315
Anders Carlsson77d81422009-03-15 17:35:16 +00005316 assertexpr.release();
5317 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005318 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005319 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005320
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005321 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005322 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005323}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005324
John McCalldd4a3b02009-09-16 22:47:08 +00005325/// Handle a friend type declaration. This works in tandem with
5326/// ActOnTag.
5327///
5328/// Notes on friend class templates:
5329///
5330/// We generally treat friend class declarations as if they were
5331/// declaring a class. So, for example, the elaborated type specifier
5332/// in a friend declaration is required to obey the restrictions of a
5333/// class-head (i.e. no typedefs in the scope chain), template
5334/// parameters are required to match up with simple template-ids, &c.
5335/// However, unlike when declaring a template specialization, it's
5336/// okay to refer to a template specialization without an empty
5337/// template parameter declaration, e.g.
5338/// friend class A<T>::B<unsigned>;
5339/// We permit this as a special case; if there are any template
5340/// parameters present at all, require proper matching, i.e.
5341/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005342Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005343 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005344 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005345
5346 assert(DS.isFriendSpecified());
5347 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5348
John McCalldd4a3b02009-09-16 22:47:08 +00005349 // Try to convert the decl specifier to a type. This works for
5350 // friend templates because ActOnTag never produces a ClassTemplateDecl
5351 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005352 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005353 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5354 if (TheDeclarator.isInvalidType())
5355 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005356
John McCalldd4a3b02009-09-16 22:47:08 +00005357 // This is definitely an error in C++98. It's probably meant to
5358 // be forbidden in C++0x, too, but the specification is just
5359 // poorly written.
5360 //
5361 // The problem is with declarations like the following:
5362 // template <T> friend A<T>::foo;
5363 // where deciding whether a class C is a friend or not now hinges
5364 // on whether there exists an instantiation of A that causes
5365 // 'foo' to equal C. There are restrictions on class-heads
5366 // (which we declare (by fiat) elaborated friend declarations to
5367 // be) that makes this tractable.
5368 //
5369 // FIXME: handle "template <> friend class A<T>;", which
5370 // is possibly well-formed? Who even knows?
5371 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5372 Diag(Loc, diag::err_tagless_friend_type_template)
5373 << DS.getSourceRange();
5374 return DeclPtrTy();
5375 }
5376
John McCall02cace72009-08-28 07:59:38 +00005377 // C++ [class.friend]p2:
5378 // An elaborated-type-specifier shall be used in a friend declaration
5379 // for a class.*
5380 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005381 // This is one of the rare places in Clang where it's legitimate to
5382 // ask about the "spelling" of the type.
5383 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5384 // If we evaluated the type to a record type, suggest putting
5385 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005386 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005387 RecordDecl *RD = RT->getDecl();
5388
5389 std::string InsertionText = std::string(" ") + RD->getKindName();
5390
John McCalle3af0232009-10-07 23:34:25 +00005391 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5392 << (unsigned) RD->getTagKind()
5393 << T
5394 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005395 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5396 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005397 return DeclPtrTy();
5398 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005399 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5400 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005401 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005402 }
5403 }
5404
John McCalle3af0232009-10-07 23:34:25 +00005405 // Enum types cannot be friends.
5406 if (T->getAs<EnumType>()) {
5407 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5408 << SourceRange(DS.getFriendSpecLoc());
5409 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005410 }
John McCall02cace72009-08-28 07:59:38 +00005411
John McCall02cace72009-08-28 07:59:38 +00005412 // C++98 [class.friend]p1: A friend of a class is a function
5413 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005414 // This is fixed in DR77, which just barely didn't make the C++03
5415 // deadline. It's also a very silly restriction that seriously
5416 // affects inner classes and which nobody else seems to implement;
5417 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005418
John McCalldd4a3b02009-09-16 22:47:08 +00005419 Decl *D;
5420 if (TempParams.size())
5421 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5422 TempParams.size(),
5423 (TemplateParameterList**) TempParams.release(),
5424 T.getTypePtr(),
5425 DS.getFriendSpecLoc());
5426 else
5427 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5428 DS.getFriendSpecLoc());
5429 D->setAccess(AS_public);
5430 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005431
John McCalldd4a3b02009-09-16 22:47:08 +00005432 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005433}
5434
John McCallbbbcdd92009-09-11 21:02:39 +00005435Sema::DeclPtrTy
5436Sema::ActOnFriendFunctionDecl(Scope *S,
5437 Declarator &D,
5438 bool IsDefinition,
5439 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005440 const DeclSpec &DS = D.getDeclSpec();
5441
5442 assert(DS.isFriendSpecified());
5443 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5444
5445 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005446 TypeSourceInfo *TInfo = 0;
5447 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005448
5449 // C++ [class.friend]p1
5450 // A friend of a class is a function or class....
5451 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005452 // It *doesn't* see through dependent types, which is correct
5453 // according to [temp.arg.type]p3:
5454 // If a declaration acquires a function type through a
5455 // type dependent on a template-parameter and this causes
5456 // a declaration that does not use the syntactic form of a
5457 // function declarator to have a function type, the program
5458 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005459 if (!T->isFunctionType()) {
5460 Diag(Loc, diag::err_unexpected_friend);
5461
5462 // It might be worthwhile to try to recover by creating an
5463 // appropriate declaration.
5464 return DeclPtrTy();
5465 }
5466
5467 // C++ [namespace.memdef]p3
5468 // - If a friend declaration in a non-local class first declares a
5469 // class or function, the friend class or function is a member
5470 // of the innermost enclosing namespace.
5471 // - The name of the friend is not found by simple name lookup
5472 // until a matching declaration is provided in that namespace
5473 // scope (either before or after the class declaration granting
5474 // friendship).
5475 // - If a friend function is called, its name may be found by the
5476 // name lookup that considers functions from namespaces and
5477 // classes associated with the types of the function arguments.
5478 // - When looking for a prior declaration of a class or a function
5479 // declared as a friend, scopes outside the innermost enclosing
5480 // namespace scope are not considered.
5481
John McCall02cace72009-08-28 07:59:38 +00005482 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5483 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005484 assert(Name);
5485
John McCall67d1a672009-08-06 02:15:43 +00005486 // The context we found the declaration in, or in which we should
5487 // create the declaration.
5488 DeclContext *DC;
5489
5490 // FIXME: handle local classes
5491
5492 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005493 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5494 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005495 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005496 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005497 DC = computeDeclContext(ScopeQual);
5498
5499 // FIXME: handle dependent contexts
5500 if (!DC) return DeclPtrTy();
5501
John McCall68263142009-11-18 22:49:29 +00005502 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005503
5504 // If searching in that context implicitly found a declaration in
5505 // a different context, treat it like it wasn't found at all.
5506 // TODO: better diagnostics for this case. Suggesting the right
5507 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005508 // FIXME: getRepresentativeDecl() is not right here at all
5509 if (Previous.empty() ||
5510 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005511 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005512 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5513 return DeclPtrTy();
5514 }
5515
5516 // C++ [class.friend]p1: A friend of a class is a function or
5517 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005518 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005519 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5520
John McCall67d1a672009-08-06 02:15:43 +00005521 // Otherwise walk out to the nearest namespace scope looking for matches.
5522 } else {
5523 // TODO: handle local class contexts.
5524
5525 DC = CurContext;
5526 while (true) {
5527 // Skip class contexts. If someone can cite chapter and verse
5528 // for this behavior, that would be nice --- it's what GCC and
5529 // EDG do, and it seems like a reasonable intent, but the spec
5530 // really only says that checks for unqualified existing
5531 // declarations should stop at the nearest enclosing namespace,
5532 // not that they should only consider the nearest enclosing
5533 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005534 while (DC->isRecord())
5535 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005536
John McCall68263142009-11-18 22:49:29 +00005537 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005538
5539 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005540 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005541 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005542
John McCall67d1a672009-08-06 02:15:43 +00005543 if (DC->isFileContext()) break;
5544 DC = DC->getParent();
5545 }
5546
5547 // C++ [class.friend]p1: A friend of a class is a function or
5548 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005549 // C++0x changes this for both friend types and functions.
5550 // Most C++ 98 compilers do seem to give an error here, so
5551 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005552 if (!Previous.empty() && DC->Equals(CurContext)
5553 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005554 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5555 }
5556
Douglas Gregor182ddf02009-09-28 00:08:27 +00005557 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005558 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005559 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5560 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5561 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005562 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005563 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5564 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005565 return DeclPtrTy();
5566 }
John McCall67d1a672009-08-06 02:15:43 +00005567 }
5568
Douglas Gregor182ddf02009-09-28 00:08:27 +00005569 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005570 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005571 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005572 IsDefinition,
5573 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005574 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005575
Douglas Gregor182ddf02009-09-28 00:08:27 +00005576 assert(ND->getDeclContext() == DC);
5577 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005578
John McCallab88d972009-08-31 22:39:49 +00005579 // Add the function declaration to the appropriate lookup tables,
5580 // adjusting the redeclarations list as necessary. We don't
5581 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005582 //
John McCallab88d972009-08-31 22:39:49 +00005583 // Also update the scope-based lookup if the target context's
5584 // lookup context is in lexical scope.
5585 if (!CurContext->isDependentContext()) {
5586 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005587 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005588 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005589 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005590 }
John McCall02cace72009-08-28 07:59:38 +00005591
5592 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005593 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005594 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005595 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005596 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005597
Douglas Gregor7557a132009-12-24 20:56:24 +00005598 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5599 FrD->setSpecialization(true);
5600
Douglas Gregor182ddf02009-09-28 00:08:27 +00005601 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005602}
5603
Chris Lattnerb28317a2009-03-28 19:18:32 +00005604void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005605 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005606
Chris Lattnerb28317a2009-03-28 19:18:32 +00005607 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005608 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5609 if (!Fn) {
5610 Diag(DelLoc, diag::err_deleted_non_function);
5611 return;
5612 }
5613 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5614 Diag(DelLoc, diag::err_deleted_decl_not_first);
5615 Diag(Prev->getLocation(), diag::note_previous_declaration);
5616 // If the declaration wasn't the first, we delete the function anyway for
5617 // recovery.
5618 }
5619 Fn->setDeleted();
5620}
Sebastian Redl13e88542009-04-27 21:33:24 +00005621
5622static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5623 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5624 ++CI) {
5625 Stmt *SubStmt = *CI;
5626 if (!SubStmt)
5627 continue;
5628 if (isa<ReturnStmt>(SubStmt))
5629 Self.Diag(SubStmt->getSourceRange().getBegin(),
5630 diag::err_return_in_constructor_handler);
5631 if (!isa<Expr>(SubStmt))
5632 SearchForReturnInStmt(Self, SubStmt);
5633 }
5634}
5635
5636void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5637 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5638 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5639 SearchForReturnInStmt(*this, Handler);
5640 }
5641}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005642
Mike Stump1eb44332009-09-09 15:08:12 +00005643bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005644 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005645 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5646 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005647
Chandler Carruth73857792010-02-15 11:53:20 +00005648 if (Context.hasSameType(NewTy, OldTy) ||
5649 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005650 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005651
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005652 // Check if the return types are covariant
5653 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005654
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005655 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005656 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5657 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005658 NewClassTy = NewPT->getPointeeType();
5659 OldClassTy = OldPT->getPointeeType();
5660 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005661 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5662 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5663 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5664 NewClassTy = NewRT->getPointeeType();
5665 OldClassTy = OldRT->getPointeeType();
5666 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005667 }
5668 }
Mike Stump1eb44332009-09-09 15:08:12 +00005669
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005670 // The return types aren't either both pointers or references to a class type.
5671 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005672 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005673 diag::err_different_return_type_for_overriding_virtual_function)
5674 << New->getDeclName() << NewTy << OldTy;
5675 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005677 return true;
5678 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005679
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005680 // C++ [class.virtual]p6:
5681 // If the return type of D::f differs from the return type of B::f, the
5682 // class type in the return type of D::f shall be complete at the point of
5683 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005684 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5685 if (!RT->isBeingDefined() &&
5686 RequireCompleteType(New->getLocation(), NewClassTy,
5687 PDiag(diag::err_covariant_return_incomplete)
5688 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005689 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005690 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005691
Douglas Gregora4923eb2009-11-16 21:35:15 +00005692 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005693 // Check if the new class derives from the old class.
5694 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5695 Diag(New->getLocation(),
5696 diag::err_covariant_return_not_derived)
5697 << New->getDeclName() << NewTy << OldTy;
5698 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5699 return true;
5700 }
Mike Stump1eb44332009-09-09 15:08:12 +00005701
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005702 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005703 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005704 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5705 // FIXME: Should this point to the return type?
5706 New->getLocation(), SourceRange(), New->getDeclName())) {
5707 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5708 return true;
5709 }
5710 }
Mike Stump1eb44332009-09-09 15:08:12 +00005711
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005712 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005713 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005714 Diag(New->getLocation(),
5715 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005716 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005717 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5718 return true;
5719 };
Mike Stump1eb44332009-09-09 15:08:12 +00005720
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005721
5722 // The new class type must have the same or less qualifiers as the old type.
5723 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5724 Diag(New->getLocation(),
5725 diag::err_covariant_return_type_class_type_more_qualified)
5726 << New->getDeclName() << NewTy << OldTy;
5727 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5728 return true;
5729 };
Mike Stump1eb44332009-09-09 15:08:12 +00005730
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005731 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005732}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005733
Sean Huntbbd37c62009-11-21 08:43:09 +00005734bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5735 const CXXMethodDecl *Old)
5736{
5737 if (Old->hasAttr<FinalAttr>()) {
5738 Diag(New->getLocation(), diag::err_final_function_overridden)
5739 << New->getDeclName();
5740 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5741 return true;
5742 }
5743
5744 return false;
5745}
5746
Douglas Gregor4ba31362009-12-01 17:24:26 +00005747/// \brief Mark the given method pure.
5748///
5749/// \param Method the method to be marked pure.
5750///
5751/// \param InitRange the source range that covers the "0" initializer.
5752bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5753 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5754 Method->setPure();
5755
5756 // A class is abstract if at least one function is pure virtual.
5757 Method->getParent()->setAbstract(true);
5758 return false;
5759 }
5760
5761 if (!Method->isInvalidDecl())
5762 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5763 << Method->getDeclName() << InitRange;
5764 return true;
5765}
5766
John McCall731ad842009-12-19 09:28:58 +00005767/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5768/// an initializer for the out-of-line declaration 'Dcl'. The scope
5769/// is a fresh scope pushed for just this purpose.
5770///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005771/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5772/// static data member of class X, names should be looked up in the scope of
5773/// class X.
5774void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005775 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005776 Decl *D = Dcl.getAs<Decl>();
5777 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005778
John McCall731ad842009-12-19 09:28:58 +00005779 // We should only get called for declarations with scope specifiers, like:
5780 // int foo::bar;
5781 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005782 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005783}
5784
5785/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005786/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005787void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005788 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005789 Decl *D = Dcl.getAs<Decl>();
5790 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005791
John McCall731ad842009-12-19 09:28:58 +00005792 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005793 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005794}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005795
5796/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5797/// C++ if/switch/while/for statement.
5798/// e.g: "if (int x = f()) {...}"
5799Action::DeclResult
5800Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5801 // C++ 6.4p2:
5802 // The declarator shall not specify a function or an array.
5803 // The type-specifier-seq shall not contain typedef and shall not declare a
5804 // new class or enumeration.
5805 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5806 "Parser allowed 'typedef' as storage class of condition decl.");
5807
John McCalla93c9342009-12-07 02:54:59 +00005808 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005809 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005810 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005811
5812 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5813 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5814 // would be created and CXXConditionDeclExpr wants a VarDecl.
5815 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5816 << D.getSourceRange();
5817 return DeclResult();
5818 } else if (OwnedTag && OwnedTag->isDefinition()) {
5819 // The type-specifier-seq shall not declare a new class or enumeration.
5820 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5821 }
5822
5823 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5824 if (!Dcl)
5825 return DeclResult();
5826
5827 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5828 VD->setDeclaredInCondition(true);
5829 return Dcl;
5830}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005831
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005832static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005833 // Ignore dependent types.
5834 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005835 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005836
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005837 // Ignore declarations that are not definitions.
5838 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005839 return false;
5840
5841 CXXRecordDecl *RD = MD->getParent();
5842
5843 // Ignore classes without a vtable.
5844 if (!RD->isDynamicClass())
5845 return false;
5846
5847 switch (MD->getParent()->getTemplateSpecializationKind()) {
5848 case TSK_Undeclared:
5849 case TSK_ExplicitSpecialization:
5850 // Classes that aren't instantiations of templates don't need their
5851 // virtual methods marked until we see the definition of the key
5852 // function.
5853 break;
5854
5855 case TSK_ImplicitInstantiation:
5856 // This is a constructor of a class template; mark all of the virtual
5857 // members as referenced to ensure that they get instantiatied.
5858 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5859 return true;
5860 break;
5861
5862 case TSK_ExplicitInstantiationDeclaration:
5863 return true; //FIXME: This looks wrong.
5864
5865 case TSK_ExplicitInstantiationDefinition:
5866 // This is method of a explicit instantiation; mark all of the virtual
5867 // members as referenced to ensure that they get instantiatied.
5868 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005869 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005870
5871 // Consider only out-of-line definitions of member functions. When we see
5872 // an inline definition, it's too early to compute the key function.
5873 if (!MD->isOutOfLine())
5874 return false;
5875
5876 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5877
5878 // If there is no key function, we will need a copy of the vtable.
5879 if (!KeyFunction)
5880 return true;
5881
5882 // If this is the key function, we need to mark virtual members.
5883 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5884 return true;
5885
5886 return false;
5887}
5888
5889void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5890 CXXMethodDecl *MD) {
5891 CXXRecordDecl *RD = MD->getParent();
5892
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005893 // We will need to mark all of the virtual members as referenced to build the
5894 // vtable.
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005895 // We actually call MarkVirtualMembersReferenced instead of adding to
5896 // ClassesWithUnmarkedVirtualMembers because this marking is needed by
5897 // codegen that will happend before we finish parsing the file.
5898 if (needsVtable(MD, Context))
5899 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005900}
5901
5902bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5903 if (ClassesWithUnmarkedVirtualMembers.empty())
5904 return false;
5905
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005906 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5907 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5908 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5909 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005910 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005911 }
5912
Anders Carlssond6a637f2009-12-07 08:24:59 +00005913 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005914}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005915
5916void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5917 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5918 e = RD->method_end(); i != e; ++i) {
5919 CXXMethodDecl *MD = *i;
5920
5921 // C++ [basic.def.odr]p2:
5922 // [...] A virtual member function is used if it is not pure. [...]
5923 if (MD->isVirtual() && !MD->isPure())
5924 MarkDeclarationReferenced(Loc, MD);
5925 }
5926}