blob: 830d2e5eef9e0db94c69d48b4c360f62822de8c3 [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
John McCall3cb0ebd2010-03-10 03:28:59 +0000668static CXXRecordDecl *GetClassForType(QualType T) {
669 if (const RecordType *RT = T->getAs<RecordType>())
670 return cast<CXXRecordDecl>(RT->getDecl());
671 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
672 return ICT->getDecl();
673 else
674 return 0;
675}
676
Douglas Gregora8f32e02009-10-06 17:59:45 +0000677/// \brief Determine whether the type \p Derived is a C++ class that is
678/// derived from the type \p Base.
679bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
680 if (!getLangOptions().CPlusPlus)
681 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000682
683 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
684 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000685 return false;
686
John McCall3cb0ebd2010-03-10 03:28:59 +0000687 CXXRecordDecl *BaseRD = GetClassForType(Base);
688 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000689 return false;
690
John McCall86ff3082010-02-04 22:26:26 +0000691 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
692 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000693}
694
695/// \brief Determine whether the type \p Derived is a C++ class that is
696/// derived from the type \p Base.
697bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
698 if (!getLangOptions().CPlusPlus)
699 return false;
700
John McCall3cb0ebd2010-03-10 03:28:59 +0000701 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
702 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000703 return false;
704
John McCall3cb0ebd2010-03-10 03:28:59 +0000705 CXXRecordDecl *BaseRD = GetClassForType(Base);
706 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000707 return false;
708
Douglas Gregora8f32e02009-10-06 17:59:45 +0000709 return DerivedRD->isDerivedFrom(BaseRD, Paths);
710}
711
712/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
713/// conversion (where Derived and Base are class types) is
714/// well-formed, meaning that the conversion is unambiguous (and
715/// that all of the base classes are accessible). Returns true
716/// and emits a diagnostic if the code is ill-formed, returns false
717/// otherwise. Loc is the location where this routine should point to
718/// if there is an error, and Range is the source range to highlight
719/// if there is an error.
720bool
721Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000722 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000723 unsigned AmbigiousBaseConvID,
724 SourceLocation Loc, SourceRange Range,
725 DeclarationName Name) {
726 // First, determine whether the path from Derived to Base is
727 // ambiguous. This is slightly more expensive than checking whether
728 // the Derived to Base conversion exists, because here we need to
729 // explore multiple paths to determine if there is an ambiguity.
730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
731 /*DetectVirtual=*/false);
732 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
733 assert(DerivationOkay &&
734 "Can only be used with a derived-to-base conversion");
735 (void)DerivationOkay;
736
737 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000738 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000739 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000740
Douglas Gregora8f32e02009-10-06 17:59:45 +0000741 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000742 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
743 Base, Derived, Paths.front(),
744 /*force*/ false,
745 /*unprivileged*/ false,
746 ADK)) {
747 case AR_accessible: return false;
748 case AR_inaccessible: return true;
749 case AR_dependent: return false;
750 case AR_delayed: return false;
751 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000752 }
753
754 // We know that the derived-to-base conversion is ambiguous, and
755 // we're going to produce a diagnostic. Perform the derived-to-base
756 // search just one more time to compute all of the possible paths so
757 // that we can print them out. This is more expensive than any of
758 // the previous derived-to-base checks we've done, but at this point
759 // performance isn't as much of an issue.
760 Paths.clear();
761 Paths.setRecordingPaths(true);
762 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
763 assert(StillOkay && "Can only be used with a derived-to-base conversion");
764 (void)StillOkay;
765
766 // Build up a textual representation of the ambiguous paths, e.g.,
767 // D -> B -> A, that will be used to illustrate the ambiguous
768 // conversions in the diagnostic. We only print one of the paths
769 // to each base class subobject.
770 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
771
772 Diag(Loc, AmbigiousBaseConvID)
773 << Derived << Base << PathDisplayStr << Range << Name;
774 return true;
775}
776
777bool
778Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000779 SourceLocation Loc, SourceRange Range,
780 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000781 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000782 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000783 diag::err_ambiguous_derived_to_base_conv,
784 Loc, Range, DeclarationName());
785}
786
787
788/// @brief Builds a string representing ambiguous paths from a
789/// specific derived class to different subobjects of the same base
790/// class.
791///
792/// This function builds a string that can be used in error messages
793/// to show the different paths that one can take through the
794/// inheritance hierarchy to go from the derived class to different
795/// subobjects of a base class. The result looks something like this:
796/// @code
797/// struct D -> struct B -> struct A
798/// struct D -> struct C -> struct A
799/// @endcode
800std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
801 std::string PathDisplayStr;
802 std::set<unsigned> DisplayedPaths;
803 for (CXXBasePaths::paths_iterator Path = Paths.begin();
804 Path != Paths.end(); ++Path) {
805 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
806 // We haven't displayed a path to this particular base
807 // class subobject yet.
808 PathDisplayStr += "\n ";
809 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
810 for (CXXBasePath::const_iterator Element = Path->begin();
811 Element != Path->end(); ++Element)
812 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
813 }
814 }
815
816 return PathDisplayStr;
817}
818
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000819//===----------------------------------------------------------------------===//
820// C++ class member Handling
821//===----------------------------------------------------------------------===//
822
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000823/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
824/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
825/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000826/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000827Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000828Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000829 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000830 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
831 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000832 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000833 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000834 Expr *BitWidth = static_cast<Expr*>(BW);
835 Expr *Init = static_cast<Expr*>(InitExpr);
836 SourceLocation Loc = D.getIdentifierLoc();
837
Sebastian Redl669d5d72008-11-14 23:42:31 +0000838 bool isFunc = D.isFunctionDeclarator();
839
John McCall67d1a672009-08-06 02:15:43 +0000840 assert(!DS.isFriendSpecified());
841
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 // C++ 9.2p6: A member shall not be declared to have automatic storage
843 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000844 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
845 // data members and cannot be applied to names declared const or static,
846 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000847 switch (DS.getStorageClassSpec()) {
848 case DeclSpec::SCS_unspecified:
849 case DeclSpec::SCS_typedef:
850 case DeclSpec::SCS_static:
851 // FALL THROUGH.
852 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000853 case DeclSpec::SCS_mutable:
854 if (isFunc) {
855 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000856 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000857 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000858 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Sebastian Redla11f42f2008-11-17 23:24:37 +0000860 // FIXME: It would be nicer if the keyword was ignored only for this
861 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000862 D.getMutableDeclSpec().ClearStorageClassSpecs();
863 } else {
864 QualType T = GetTypeForDeclarator(D, S);
865 diag::kind err = static_cast<diag::kind>(0);
866 if (T->isReferenceType())
867 err = diag::err_mutable_reference;
868 else if (T.isConstQualified())
869 err = diag::err_mutable_const;
870 if (err != 0) {
871 if (DS.getStorageClassSpecLoc().isValid())
872 Diag(DS.getStorageClassSpecLoc(), err);
873 else
874 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000875 // FIXME: It would be nicer if the keyword was ignored only for this
876 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000877 D.getMutableDeclSpec().ClearStorageClassSpecs();
878 }
879 }
880 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000881 default:
882 if (DS.getStorageClassSpecLoc().isValid())
883 Diag(DS.getStorageClassSpecLoc(),
884 diag::err_storageclass_invalid_for_member);
885 else
886 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
887 D.getMutableDeclSpec().ClearStorageClassSpecs();
888 }
889
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000890 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000891 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000892 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000893 // Check also for this case:
894 //
895 // typedef int f();
896 // f a;
897 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000898 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000899 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000900 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901
Sebastian Redl669d5d72008-11-14 23:42:31 +0000902 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
903 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000904 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000905
906 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000907 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000908 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000909 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
910 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000911 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000912 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000913 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000914 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000915 if (!Member) {
916 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000917 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000918 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000919
920 // Non-instance-fields can't have a bitfield.
921 if (BitWidth) {
922 if (Member->isInvalidDecl()) {
923 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000924 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000925 // C++ 9.6p3: A bit-field shall not be a static member.
926 // "static member 'A' cannot be a bit-field"
927 Diag(Loc, diag::err_static_not_bitfield)
928 << Name << BitWidth->getSourceRange();
929 } else if (isa<TypedefDecl>(Member)) {
930 // "typedef member 'x' cannot be a bit-field"
931 Diag(Loc, diag::err_typedef_not_bitfield)
932 << Name << BitWidth->getSourceRange();
933 } else {
934 // A function typedef ("typedef int f(); f a;").
935 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
936 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000937 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000938 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000939 }
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner8b963ef2009-03-05 23:01:03 +0000941 DeleteExpr(BitWidth);
942 BitWidth = 0;
943 Member->setInvalidDecl();
944 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000945
946 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor37b372b2009-08-20 22:52:58 +0000948 // If we have declared a member function template, set the access of the
949 // templated declaration as well.
950 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
951 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000952 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000953
Douglas Gregor10bd3682008-11-17 22:58:34 +0000954 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000955
Douglas Gregor021c3b32009-03-11 23:00:04 +0000956 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000957 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000958 if (Deleted) // FIXME: Source location is not very good.
959 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000960
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000961 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000962 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000963 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000964 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000965 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000966}
967
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000968/// \brief Find the direct and/or virtual base specifiers that
969/// correspond to the given base type, for use in base initialization
970/// within a constructor.
971static bool FindBaseInitializer(Sema &SemaRef,
972 CXXRecordDecl *ClassDecl,
973 QualType BaseType,
974 const CXXBaseSpecifier *&DirectBaseSpec,
975 const CXXBaseSpecifier *&VirtualBaseSpec) {
976 // First, check for a direct base class.
977 DirectBaseSpec = 0;
978 for (CXXRecordDecl::base_class_const_iterator Base
979 = ClassDecl->bases_begin();
980 Base != ClassDecl->bases_end(); ++Base) {
981 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
982 // We found a direct base of this type. That's what we're
983 // initializing.
984 DirectBaseSpec = &*Base;
985 break;
986 }
987 }
988
989 // Check for a virtual base class.
990 // FIXME: We might be able to short-circuit this if we know in advance that
991 // there are no virtual bases.
992 VirtualBaseSpec = 0;
993 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
994 // We haven't found a base yet; search the class hierarchy for a
995 // virtual base class.
996 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
997 /*DetectVirtual=*/false);
998 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
999 BaseType, Paths)) {
1000 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1001 Path != Paths.end(); ++Path) {
1002 if (Path->back().Base->isVirtual()) {
1003 VirtualBaseSpec = Path->back().Base;
1004 break;
1005 }
1006 }
1007 }
1008 }
1009
1010 return DirectBaseSpec || VirtualBaseSpec;
1011}
1012
Douglas Gregor7ad83902008-11-05 04:29:56 +00001013/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001014Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001015Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001016 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001017 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001018 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001019 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001020 SourceLocation IdLoc,
1021 SourceLocation LParenLoc,
1022 ExprTy **Args, unsigned NumArgs,
1023 SourceLocation *CommaLocs,
1024 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001025 if (!ConstructorD)
1026 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001028 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
1030 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001031 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001032 if (!Constructor) {
1033 // The user wrote a constructor initializer on a function that is
1034 // not a C++ constructor. Ignore the error for now, because we may
1035 // have more member initializers coming; we'll diagnose it just
1036 // once in ActOnMemInitializers.
1037 return true;
1038 }
1039
1040 CXXRecordDecl *ClassDecl = Constructor->getParent();
1041
1042 // C++ [class.base.init]p2:
1043 // Names in a mem-initializer-id are looked up in the scope of the
1044 // constructor’s class and, if not found in that scope, are looked
1045 // up in the scope containing the constructor’s
1046 // definition. [Note: if the constructor’s class contains a member
1047 // with the same name as a direct or virtual base class of the
1048 // class, a mem-initializer-id naming the member or base class and
1049 // composed of a single identifier refers to the class member. A
1050 // mem-initializer-id for the hidden base class may be specified
1051 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001052 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001053 // Look for a member, first.
1054 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001055 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001056 = ClassDecl->lookup(MemberOrBase);
1057 if (Result.first != Result.second)
1058 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001059
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001060 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061
Eli Friedman59c04372009-07-29 19:44:27 +00001062 if (Member)
1063 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001064 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001065 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001066 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001067 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001068 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001069
1070 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001071 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001072 } else {
1073 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1074 LookupParsedName(R, S, &SS);
1075
1076 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1077 if (!TyD) {
1078 if (R.isAmbiguous()) return true;
1079
Douglas Gregor7a886e12010-01-19 06:46:48 +00001080 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1081 bool NotUnknownSpecialization = false;
1082 DeclContext *DC = computeDeclContext(SS, false);
1083 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1084 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1085
1086 if (!NotUnknownSpecialization) {
1087 // When the scope specifier can refer to a member of an unknown
1088 // specialization, we take it as a type name.
1089 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1090 *MemberOrBase, SS.getRange());
Douglas Gregora50ce322010-03-07 23:26:22 +00001091 if (BaseType.isNull())
1092 return true;
1093
Douglas Gregor7a886e12010-01-19 06:46:48 +00001094 R.clear();
1095 }
1096 }
1097
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001098 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001099 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001100 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1101 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1102 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1103 // We have found a non-static data member with a similar
1104 // name to what was typed; complain and initialize that
1105 // member.
1106 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1107 << MemberOrBase << true << R.getLookupName()
1108 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1109 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001110 Diag(Member->getLocation(), diag::note_previous_decl)
1111 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001112
1113 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1114 LParenLoc, RParenLoc);
1115 }
1116 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1117 const CXXBaseSpecifier *DirectBaseSpec;
1118 const CXXBaseSpecifier *VirtualBaseSpec;
1119 if (FindBaseInitializer(*this, ClassDecl,
1120 Context.getTypeDeclType(Type),
1121 DirectBaseSpec, VirtualBaseSpec)) {
1122 // We have found a direct or virtual base class with a
1123 // similar name to what was typed; complain and initialize
1124 // that base class.
1125 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1126 << MemberOrBase << false << R.getLookupName()
1127 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1128 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001129
1130 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1131 : VirtualBaseSpec;
1132 Diag(BaseSpec->getSourceRange().getBegin(),
1133 diag::note_base_class_specified_here)
1134 << BaseSpec->getType()
1135 << BaseSpec->getSourceRange();
1136
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001137 TyD = Type;
1138 }
1139 }
1140 }
1141
Douglas Gregor7a886e12010-01-19 06:46:48 +00001142 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001143 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1144 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1145 return true;
1146 }
John McCall2b194412009-12-21 10:41:20 +00001147 }
1148
Douglas Gregor7a886e12010-01-19 06:46:48 +00001149 if (BaseType.isNull()) {
1150 BaseType = Context.getTypeDeclType(TyD);
1151 if (SS.isSet()) {
1152 NestedNameSpecifier *Qualifier =
1153 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001154
Douglas Gregor7a886e12010-01-19 06:46:48 +00001155 // FIXME: preserve source range information
1156 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1157 }
John McCall2b194412009-12-21 10:41:20 +00001158 }
1159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCalla93c9342009-12-07 02:54:59 +00001161 if (!TInfo)
1162 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001163
John McCalla93c9342009-12-07 02:54:59 +00001164 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001165 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001166}
1167
John McCallb4190042009-11-04 23:02:40 +00001168/// Checks an initializer expression for use of uninitialized fields, such as
1169/// containing the field that is being initialized. Returns true if there is an
1170/// uninitialized field was used an updates the SourceLocation parameter; false
1171/// otherwise.
1172static bool InitExprContainsUninitializedFields(const Stmt* S,
1173 const FieldDecl* LhsField,
1174 SourceLocation* L) {
1175 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1176 if (ME) {
1177 const NamedDecl* RhsField = ME->getMemberDecl();
1178 if (RhsField == LhsField) {
1179 // Initializing a field with itself. Throw a warning.
1180 // But wait; there are exceptions!
1181 // Exception #1: The field may not belong to this record.
1182 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1183 const Expr* base = ME->getBase();
1184 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1185 // Even though the field matches, it does not belong to this record.
1186 return false;
1187 }
1188 // None of the exceptions triggered; return true to indicate an
1189 // uninitialized field was used.
1190 *L = ME->getMemberLoc();
1191 return true;
1192 }
1193 }
1194 bool found = false;
1195 for (Stmt::const_child_iterator it = S->child_begin();
1196 it != S->child_end() && found == false;
1197 ++it) {
1198 if (isa<CallExpr>(S)) {
1199 // Do not descend into function calls or constructors, as the use
1200 // of an uninitialized field may be valid. One would have to inspect
1201 // the contents of the function/ctor to determine if it is safe or not.
1202 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1203 // may be safe, depending on what the function/ctor does.
1204 continue;
1205 }
1206 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1207 }
1208 return found;
1209}
1210
Eli Friedman59c04372009-07-29 19:44:27 +00001211Sema::MemInitResult
1212Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1213 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001214 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001215 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001216 // Diagnose value-uses of fields to initialize themselves, e.g.
1217 // foo(foo)
1218 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001219 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001220 for (unsigned i = 0; i < NumArgs; ++i) {
1221 SourceLocation L;
1222 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1223 // FIXME: Return true in the case when other fields are used before being
1224 // uninitialized. For example, let this field be the i'th field. When
1225 // initializing the i'th field, throw a warning if any of the >= i'th
1226 // fields are used, as they are not yet initialized.
1227 // Right now we are only handling the case where the i'th field uses
1228 // itself in its initializer.
1229 Diag(L, diag::warn_field_is_uninit);
1230 }
1231 }
1232
Eli Friedman59c04372009-07-29 19:44:27 +00001233 bool HasDependentArg = false;
1234 for (unsigned i = 0; i < NumArgs; i++)
1235 HasDependentArg |= Args[i]->isTypeDependent();
1236
Eli Friedman59c04372009-07-29 19:44:27 +00001237 QualType FieldType = Member->getType();
1238 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1239 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001240 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001241 if (FieldType->isDependentType() || HasDependentArg) {
1242 // Can't check initialization for a member of dependent type or when
1243 // any of the arguments are type-dependent expressions.
1244 OwningExprResult Init
1245 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1246 RParenLoc));
1247
1248 // Erase any temporaries within this evaluation context; we're not
1249 // going to track them in the AST, since we'll be rebuilding the
1250 // ASTs during template instantiation.
1251 ExprTemporaries.erase(
1252 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1253 ExprTemporaries.end());
1254
1255 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1256 LParenLoc,
1257 Init.takeAs<Expr>(),
1258 RParenLoc);
1259
Douglas Gregor7ad83902008-11-05 04:29:56 +00001260 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001261
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001262 if (Member->isInvalidDecl())
1263 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001264
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001265 // Initialize the member.
1266 InitializedEntity MemberEntity =
1267 InitializedEntity::InitializeMember(Member, 0);
1268 InitializationKind Kind =
1269 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1270
1271 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1272
1273 OwningExprResult MemberInit =
1274 InitSeq.Perform(*this, MemberEntity, Kind,
1275 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1276 if (MemberInit.isInvalid())
1277 return true;
1278
1279 // C++0x [class.base.init]p7:
1280 // The initialization of each base and member constitutes a
1281 // full-expression.
1282 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1283 if (MemberInit.isInvalid())
1284 return true;
1285
1286 // If we are in a dependent context, template instantiation will
1287 // perform this type-checking again. Just save the arguments that we
1288 // received in a ParenListExpr.
1289 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1290 // of the information that we have about the member
1291 // initializer. However, deconstructing the ASTs is a dicey process,
1292 // and this approach is far more likely to get the corner cases right.
1293 if (CurContext->isDependentContext()) {
1294 // Bump the reference count of all of the arguments.
1295 for (unsigned I = 0; I != NumArgs; ++I)
1296 Args[I]->Retain();
1297
1298 OwningExprResult Init
1299 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1300 RParenLoc));
1301 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1302 LParenLoc,
1303 Init.takeAs<Expr>(),
1304 RParenLoc);
1305 }
1306
Douglas Gregor802ab452009-12-02 22:36:29 +00001307 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001308 LParenLoc,
1309 MemberInit.takeAs<Expr>(),
1310 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001311}
1312
1313Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001314Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001315 Expr **Args, unsigned NumArgs,
1316 SourceLocation LParenLoc, SourceLocation RParenLoc,
1317 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001318 bool HasDependentArg = false;
1319 for (unsigned i = 0; i < NumArgs; i++)
1320 HasDependentArg |= Args[i]->isTypeDependent();
1321
John McCalla93c9342009-12-07 02:54:59 +00001322 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001323 if (BaseType->isDependentType() || HasDependentArg) {
1324 // Can't check initialization for a base of dependent type or when
1325 // any of the arguments are type-dependent expressions.
1326 OwningExprResult BaseInit
1327 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1328 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001329
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001330 // Erase any temporaries within this evaluation context; we're not
1331 // going to track them in the AST, since we'll be rebuilding the
1332 // ASTs during template instantiation.
1333 ExprTemporaries.erase(
1334 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1335 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001337 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1338 LParenLoc,
1339 BaseInit.takeAs<Expr>(),
1340 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001341 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001342
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001343 if (!BaseType->isRecordType())
1344 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1345 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1346
1347 // C++ [class.base.init]p2:
1348 // [...] Unless the mem-initializer-id names a nonstatic data
1349 // member of the constructor’s class or a direct or virtual base
1350 // of that class, the mem-initializer is ill-formed. A
1351 // mem-initializer-list can initialize a base class using any
1352 // name that denotes that base class type.
1353
1354 // Check for direct and virtual base classes.
1355 const CXXBaseSpecifier *DirectBaseSpec = 0;
1356 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1357 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1358 VirtualBaseSpec);
1359
1360 // C++ [base.class.init]p2:
1361 // If a mem-initializer-id is ambiguous because it designates both
1362 // a direct non-virtual base class and an inherited virtual base
1363 // class, the mem-initializer is ill-formed.
1364 if (DirectBaseSpec && VirtualBaseSpec)
1365 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1366 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1367 // C++ [base.class.init]p2:
1368 // Unless the mem-initializer-id names a nonstatic data membeer of the
1369 // constructor's class ot a direst or virtual base of that class, the
1370 // mem-initializer is ill-formed.
1371 if (!DirectBaseSpec && !VirtualBaseSpec)
1372 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1373 << BaseType << ClassDecl->getNameAsCString()
1374 << BaseTInfo->getTypeLoc().getSourceRange();
1375
1376 CXXBaseSpecifier *BaseSpec
1377 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1378 if (!BaseSpec)
1379 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1380
1381 // Initialize the base.
1382 InitializedEntity BaseEntity =
1383 InitializedEntity::InitializeBase(Context, BaseSpec);
1384 InitializationKind Kind =
1385 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1386
1387 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1388
1389 OwningExprResult BaseInit =
1390 InitSeq.Perform(*this, BaseEntity, Kind,
1391 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1392 if (BaseInit.isInvalid())
1393 return true;
1394
1395 // C++0x [class.base.init]p7:
1396 // The initialization of each base and member constitutes a
1397 // full-expression.
1398 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1399 if (BaseInit.isInvalid())
1400 return true;
1401
1402 // If we are in a dependent context, template instantiation will
1403 // perform this type-checking again. Just save the arguments that we
1404 // received in a ParenListExpr.
1405 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1406 // of the information that we have about the base
1407 // initializer. However, deconstructing the ASTs is a dicey process,
1408 // and this approach is far more likely to get the corner cases right.
1409 if (CurContext->isDependentContext()) {
1410 // Bump the reference count of all of the arguments.
1411 for (unsigned I = 0; I != NumArgs; ++I)
1412 Args[I]->Retain();
1413
1414 OwningExprResult Init
1415 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1416 RParenLoc));
1417 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1418 LParenLoc,
1419 Init.takeAs<Expr>(),
1420 RParenLoc);
1421 }
1422
1423 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1424 LParenLoc,
1425 BaseInit.takeAs<Expr>(),
1426 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001427}
1428
Eli Friedman80c30da2009-11-09 19:20:36 +00001429bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001430Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001431 CXXBaseOrMemberInitializer **Initializers,
1432 unsigned NumInitializers,
1433 bool IsImplicitConstructor,
1434 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001435 // We need to build the initializer AST according to order of construction
1436 // and not what user specified in the Initializers list.
1437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1438 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1439 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1440 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001441 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001443 for (unsigned i = 0; i < NumInitializers; i++) {
1444 CXXBaseOrMemberInitializer *Member = Initializers[i];
1445 if (Member->isBaseInitializer()) {
1446 if (Member->getBaseClass()->isDependentType())
1447 HasDependentBaseInit = true;
1448 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1449 } else {
1450 AllBaseFields[Member->getMember()] = Member;
1451 }
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001454 if (HasDependentBaseInit) {
1455 // FIXME. This does not preserve the ordering of the initializers.
1456 // Try (with -Wreorder)
1457 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // template<class X> struct B : A<X> {
1459 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460 // int x1;
1461 // };
1462 // B<int> x;
1463 // On seeing one dependent type, we should essentially exit this routine
1464 // while preserving user-declared initializer list. When this routine is
1465 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001466 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001468 // If we have a dependent base initialization, we can't determine the
1469 // association between initializers and bases; just dump the known
1470 // initializers into the list, and don't try to deal with other bases.
1471 for (unsigned i = 0; i < NumInitializers; i++) {
1472 CXXBaseOrMemberInitializer *Member = Initializers[i];
1473 if (Member->isBaseInitializer())
1474 AllToInit.push_back(Member);
1475 }
1476 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001477 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1478
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001479 // Push virtual bases before others.
1480 for (CXXRecordDecl::base_class_iterator VBase =
1481 ClassDecl->vbases_begin(),
1482 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1483 if (VBase->getType()->isDependentType())
1484 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001485 if (CXXBaseOrMemberInitializer *Value
1486 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001487 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001488 } else if (!AnyErrors) {
1489 InitializedEntity InitEntity
1490 = InitializedEntity::InitializeBase(Context, VBase);
1491 InitializationKind InitKind
1492 = InitializationKind::CreateDefault(Constructor->getLocation());
1493 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1494 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1495 MultiExprArg(*this, 0, 0));
1496 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1497 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001498 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001499 continue;
1500 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001501
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001502 // Don't attach synthesized base initializers in a dependent
1503 // context; they'll be checked again at template instantiation
1504 // time.
1505 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001506 continue;
1507
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001508 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001509 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001510 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001511 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001512 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001513 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001514 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001515 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001516 }
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001519 for (CXXRecordDecl::base_class_iterator Base =
1520 ClassDecl->bases_begin(),
1521 E = ClassDecl->bases_end(); Base != E; ++Base) {
1522 // Virtuals are in the virtual base list and already constructed.
1523 if (Base->isVirtual())
1524 continue;
1525 // Skip dependent types.
1526 if (Base->getType()->isDependentType())
1527 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001528 if (CXXBaseOrMemberInitializer *Value
1529 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001530 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001531 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001532 else if (!AnyErrors) {
1533 InitializedEntity InitEntity
1534 = InitializedEntity::InitializeBase(Context, Base);
1535 InitializationKind InitKind
1536 = InitializationKind::CreateDefault(Constructor->getLocation());
1537 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1538 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1539 MultiExprArg(*this, 0, 0));
1540 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1541 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001542 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001543 continue;
1544 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001545
1546 // Don't attach synthesized base initializers in a dependent
1547 // context; they'll be regenerated at template instantiation
1548 // time.
1549 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001550 continue;
1551
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001552 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001553 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001554 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001555 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001556 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001557 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001558 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001559 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001560 }
1561 }
1562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001564 // non-static data members.
1565 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1566 E = ClassDecl->field_end(); Field != E; ++Field) {
1567 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001568 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001569 Field->getType()->getAs<RecordType>()) {
1570 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001571 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001572 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001573 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1574 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1575 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1576 // set to the anonymous union data member used in the initializer
1577 // list.
1578 Value->setMember(*Field);
1579 Value->setAnonUnionMember(*FA);
1580 AllToInit.push_back(Value);
1581 break;
1582 }
1583 }
1584 }
1585 continue;
1586 }
1587 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1588 AllToInit.push_back(Value);
1589 continue;
1590 }
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001592 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001593 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001594
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001595 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001596 if (FT->getAs<RecordType>()) {
1597 InitializedEntity InitEntity
1598 = InitializedEntity::InitializeMember(*Field);
1599 InitializationKind InitKind
1600 = InitializationKind::CreateDefault(Constructor->getLocation());
1601
1602 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1603 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1604 MultiExprArg(*this, 0, 0));
1605 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1606 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001607 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001608 continue;
1609 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610
1611 // Don't attach synthesized member initializers in a dependent
1612 // context; they'll be regenerated a template instantiation
1613 // time.
1614 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001615 continue;
1616
Mike Stump1eb44332009-09-09 15:08:12 +00001617 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001618 new (Context) CXXBaseOrMemberInitializer(Context,
1619 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001620 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001621 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001622 SourceLocation());
1623
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001624 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001625 }
1626 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001627 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001628 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1629 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001630 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001631 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001632 }
1633 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001634 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001635 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1636 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001637 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001638 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001639 }
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001642 NumInitializers = AllToInit.size();
1643 if (NumInitializers > 0) {
1644 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1645 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1646 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001648 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001649 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1650 CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1651 baseOrMemberInitializers[Idx] = Member;
1652 if (!Member->isBaseInitializer())
1653 continue;
1654 const Type *BaseType = Member->getBaseClass();
1655 const RecordType *RT = BaseType->getAs<RecordType>();
1656 if (!RT)
1657 continue;
1658 CXXRecordDecl *BaseClassDecl =
1659 cast<CXXRecordDecl>(RT->getDecl());
1660 if (BaseClassDecl->hasTrivialDestructor())
1661 continue;
1662 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1663 MarkDeclarationReferenced(Constructor->getLocation(), DD);
1664 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001665 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001666
1667 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001668}
1669
Eli Friedman6347f422009-07-21 19:28:10 +00001670static void *GetKeyForTopLevelField(FieldDecl *Field) {
1671 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001672 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001673 if (RT->getDecl()->isAnonymousStructOrUnion())
1674 return static_cast<void *>(RT->getDecl());
1675 }
1676 return static_cast<void *>(Field);
1677}
1678
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001679static void *GetKeyForBase(QualType BaseType) {
1680 if (const RecordType *RT = BaseType->getAs<RecordType>())
1681 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001683 assert(0 && "Unexpected base type!");
1684 return 0;
1685}
1686
Mike Stump1eb44332009-09-09 15:08:12 +00001687static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001688 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001689 // For fields injected into the class via declaration of an anonymous union,
1690 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001691 if (Member->isMemberInitializer()) {
1692 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Eli Friedman49c16da2009-11-09 01:05:47 +00001694 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001695 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001696 // in AnonUnionMember field.
1697 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1698 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001699 if (Field->getDeclContext()->isRecord()) {
1700 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1701 if (RD->isAnonymousStructOrUnion())
1702 return static_cast<void *>(RD);
1703 }
1704 return static_cast<void *>(Field);
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001707 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001708}
1709
John McCall6aee6212009-11-04 23:13:52 +00001710/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001711void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001712 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001713 MemInitTy **MemInits, unsigned NumMemInits,
1714 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001715 if (!ConstructorDecl)
1716 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001717
1718 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001719
1720 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001721 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Anders Carlssona7b35212009-03-25 02:58:17 +00001723 if (!Constructor) {
1724 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1725 return;
1726 }
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001728 if (!Constructor->isDependentContext()) {
1729 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1730 bool err = false;
1731 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001732 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001733 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1734 void *KeyToMember = GetKeyForMember(Member);
1735 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1736 if (!PrevMember) {
1737 PrevMember = Member;
1738 continue;
1739 }
1740 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001741 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001742 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001743 << Field->getNameAsString()
1744 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001745 else {
1746 Type *BaseClass = Member->getBaseClass();
1747 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001748 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001749 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001750 << QualType(BaseClass, 0)
1751 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001752 }
1753 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1754 << 0;
1755 err = true;
1756 }
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001758 if (err)
1759 return;
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Eli Friedman49c16da2009-11-09 01:05:47 +00001762 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001763 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001764 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001766 if (Constructor->isDependentContext())
1767 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001768
1769 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001770 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001771 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001772 Diagnostic::Ignored)
1773 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001775 // Also issue warning if order of ctor-initializer list does not match order
1776 // of 1) base class declarations and 2) order of non-static data members.
1777 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001779 CXXRecordDecl *ClassDecl
1780 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1781 // Push virtual bases before others.
1782 for (CXXRecordDecl::base_class_iterator VBase =
1783 ClassDecl->vbases_begin(),
1784 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001785 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001787 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1788 E = ClassDecl->bases_end(); Base != E; ++Base) {
1789 // Virtuals are alread in the virtual base list and are constructed
1790 // first.
1791 if (Base->isVirtual())
1792 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001793 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001794 }
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001796 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1797 E = ClassDecl->field_end(); Field != E; ++Field)
1798 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001800 int Last = AllBaseOrMembers.size();
1801 int curIndex = 0;
1802 CXXBaseOrMemberInitializer *PrevMember = 0;
1803 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001804 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001805 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1806 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001807
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001808 for (; curIndex < Last; curIndex++)
1809 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1810 break;
1811 if (curIndex == Last) {
1812 assert(PrevMember && "Member not in member list?!");
1813 // Initializer as specified in ctor-initializer list is out of order.
1814 // Issue a warning diagnostic.
1815 if (PrevMember->isBaseInitializer()) {
1816 // Diagnostics is for an initialized base class.
1817 Type *BaseClass = PrevMember->getBaseClass();
1818 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001819 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001820 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001821 } else {
1822 FieldDecl *Field = PrevMember->getMember();
1823 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001824 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001825 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001826 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001827 // Also the note!
1828 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001829 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001830 diag::note_fieldorbase_initialized_here) << 0
1831 << Field->getNameAsString();
1832 else {
1833 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001834 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001835 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001836 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001837 }
1838 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001839 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001840 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001841 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001842 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001843 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001844}
1845
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001846void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001847Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1848 // Ignore dependent destructors.
1849 if (Destructor->isDependentContext())
1850 return;
1851
1852 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Anders Carlsson9f853df2009-11-17 04:44:12 +00001854 // Non-static data members.
1855 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1856 E = ClassDecl->field_end(); I != E; ++I) {
1857 FieldDecl *Field = *I;
1858
1859 QualType FieldType = Context.getBaseElementType(Field->getType());
1860
1861 const RecordType* RT = FieldType->getAs<RecordType>();
1862 if (!RT)
1863 continue;
1864
1865 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1866 if (FieldClassDecl->hasTrivialDestructor())
1867 continue;
1868
1869 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1870 MarkDeclarationReferenced(Destructor->getLocation(),
1871 const_cast<CXXDestructorDecl*>(Dtor));
1872 }
1873
1874 // Bases.
1875 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1876 E = ClassDecl->bases_end(); Base != E; ++Base) {
1877 // Ignore virtual bases.
1878 if (Base->isVirtual())
1879 continue;
1880
1881 // Ignore trivial destructors.
1882 CXXRecordDecl *BaseClassDecl
1883 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1884 if (BaseClassDecl->hasTrivialDestructor())
1885 continue;
1886
1887 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1888 MarkDeclarationReferenced(Destructor->getLocation(),
1889 const_cast<CXXDestructorDecl*>(Dtor));
1890 }
1891
1892 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001893 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1894 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001895 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001896 CXXRecordDecl *BaseClassDecl
1897 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1898 if (BaseClassDecl->hasTrivialDestructor())
1899 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001900
1901 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1902 MarkDeclarationReferenced(Destructor->getLocation(),
1903 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001904 }
1905}
1906
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001907void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001908 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001909 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001911 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
1913 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001914 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001915 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001916}
1917
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001918namespace {
1919 /// PureVirtualMethodCollector - traverses a class and its superclasses
1920 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001921 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001922 ASTContext &Context;
1923
Sebastian Redldfe292d2009-03-22 21:28:55 +00001924 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001925 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001926
1927 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001928 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001930 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001932 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001933 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001934 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001936 MethodList List;
1937 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001939 // Copy the temporary list to methods, and make sure to ignore any
1940 // null entries.
1941 for (size_t i = 0, e = List.size(); i != e; ++i) {
1942 if (List[i])
1943 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001944 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001947 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001949 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1950 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001951 };
Mike Stump1eb44332009-09-09 15:08:12 +00001952
1953 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001954 MethodList& Methods) {
1955 // First, collect the pure virtual methods for the base classes.
1956 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1957 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001958 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001959 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001960 if (BaseDecl && BaseDecl->isAbstract())
1961 Collect(BaseDecl, Methods);
1962 }
1963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001965 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001966 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001968 MethodSetTy OverriddenMethods;
1969 size_t MethodsSize = Methods.size();
1970
Mike Stump1eb44332009-09-09 15:08:12 +00001971 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001972 i != e; ++i) {
1973 // Traverse the record, looking for methods.
1974 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001975 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001976 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001977 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Anders Carlsson27823022009-10-18 19:34:08 +00001979 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001980 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1981 E = MD->end_overridden_methods(); I != E; ++I) {
1982 // Keep track of the overridden methods.
1983 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001984 }
1985 }
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
1988 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001989 // overridden.
1990 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1991 if (OverriddenMethods.count(Methods[i]))
1992 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001993 }
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001995 }
1996}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001997
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001998
Mike Stump1eb44332009-09-09 15:08:12 +00001999bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002000 unsigned DiagID, AbstractDiagSelID SelID,
2001 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002002 if (SelID == -1)
2003 return RequireNonAbstractType(Loc, T,
2004 PDiag(DiagID), CurrentRD);
2005 else
2006 return RequireNonAbstractType(Loc, T,
2007 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002008}
2009
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002010bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2011 const PartialDiagnostic &PD,
2012 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002013 if (!getLangOptions().CPlusPlus)
2014 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Anders Carlsson11f21a02009-03-23 19:10:31 +00002016 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002017 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002018 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002021 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002022 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002023 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002025 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002026 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenek6217b802009-07-29 21:53:49 +00002029 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002030 if (!RT)
2031 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
John McCall86ff3082010-02-04 22:26:26 +00002033 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002034
Anders Carlssone65a3c82009-03-24 17:23:42 +00002035 if (CurrentRD && CurrentRD != RD)
2036 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002037
John McCall86ff3082010-02-04 22:26:26 +00002038 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002039 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002040 return false;
2041
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002042 if (!RD->isAbstract())
2043 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002045 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002047 // Check if we've already emitted the list of pure virtual functions for this
2048 // class.
2049 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2050 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002052 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
2054 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002055 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2056 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
2058 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002059 MD->getDeclName();
2060 }
2061
2062 if (!PureVirtualClassDiagSet)
2063 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2064 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002066 return true;
2067}
2068
Anders Carlsson8211eff2009-03-24 01:19:16 +00002069namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002070 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002071 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2072 Sema &SemaRef;
2073 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Anders Carlssone65a3c82009-03-24 17:23:42 +00002075 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002076 bool Invalid = false;
2077
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002078 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2079 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002080 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002081
Anders Carlsson8211eff2009-03-24 01:19:16 +00002082 return Invalid;
2083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Anders Carlssone65a3c82009-03-24 17:23:42 +00002085 public:
2086 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2087 : SemaRef(SemaRef), AbstractClass(ac) {
2088 Visit(SemaRef.Context.getTranslationUnitDecl());
2089 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002090
Anders Carlssone65a3c82009-03-24 17:23:42 +00002091 bool VisitFunctionDecl(const FunctionDecl *FD) {
2092 if (FD->isThisDeclarationADefinition()) {
2093 // No need to do the check if we're in a definition, because it requires
2094 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002095 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002096 return VisitDeclContext(FD);
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Anders Carlssone65a3c82009-03-24 17:23:42 +00002099 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002100 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002101 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002102 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2103 diag::err_abstract_type_in_decl,
2104 Sema::AbstractReturnType,
2105 AbstractClass);
2106
Mike Stump1eb44332009-09-09 15:08:12 +00002107 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002108 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002109 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002110 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002111 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002112 VD->getOriginalType(),
2113 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002114 Sema::AbstractParamType,
2115 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002116 }
2117
2118 return Invalid;
2119 }
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Anders Carlssone65a3c82009-03-24 17:23:42 +00002121 bool VisitDecl(const Decl* D) {
2122 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2123 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Anders Carlssone65a3c82009-03-24 17:23:42 +00002125 return false;
2126 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002127 };
2128}
2129
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002130/// \brief Perform semantic checks on a class definition that has been
2131/// completing, introducing implicitly-declared members, checking for
2132/// abstract types, etc.
2133void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2134 if (!Record || Record->isInvalidDecl())
2135 return;
2136
Eli Friedmanff2d8782009-12-16 20:00:27 +00002137 if (!Record->isDependentType())
2138 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002139
Eli Friedmanff2d8782009-12-16 20:00:27 +00002140 if (Record->isInvalidDecl())
2141 return;
2142
John McCall233a6412010-01-28 07:38:46 +00002143 // Set access bits correctly on the directly-declared conversions.
2144 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2145 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2146 Convs->setAccess(I, (*I)->getAccess());
2147
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002148 if (!Record->isAbstract()) {
2149 // Collect all the pure virtual methods and see if this is an abstract
2150 // class after all.
2151 PureVirtualMethodCollector Collector(Context, Record);
2152 if (!Collector.empty())
2153 Record->setAbstract(true);
2154 }
2155
2156 if (Record->isAbstract())
2157 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002158}
2159
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002160void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002161 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002162 SourceLocation LBrac,
2163 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002164 if (!TagDecl)
2165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor42af25f2009-05-11 19:58:34 +00002167 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002168
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002169 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002170 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002171 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002172
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002173 CheckCompletedCXXClass(
2174 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002175}
2176
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002177/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2178/// special functions, such as the default constructor, copy
2179/// constructor, or destructor, to the given C++ class (C++
2180/// [special]p1). This routine can only be executed just before the
2181/// definition of the class is complete.
2182void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002183 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002184 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002185
Sebastian Redl465226e2009-05-27 22:11:52 +00002186 // FIXME: Implicit declarations have exception specifications, which are
2187 // the union of the specifications of the implicitly called functions.
2188
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002189 if (!ClassDecl->hasUserDeclaredConstructor()) {
2190 // C++ [class.ctor]p5:
2191 // A default constructor for a class X is a constructor of class X
2192 // that can be called without an argument. If there is no
2193 // user-declared constructor for class X, a default constructor is
2194 // implicitly declared. An implicitly-declared default constructor
2195 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002196 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002197 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002198 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002199 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002200 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002201 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002202 0, 0, false, 0,
2203 /*FIXME*/false, false,
2204 0, 0, false,
2205 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002206 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002207 /*isExplicit=*/false,
2208 /*isInline=*/true,
2209 /*isImplicitlyDeclared=*/true);
2210 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002211 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002212 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002213 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002214 }
2215
2216 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2217 // C++ [class.copy]p4:
2218 // If the class definition does not explicitly declare a copy
2219 // constructor, one is declared implicitly.
2220
2221 // C++ [class.copy]p5:
2222 // The implicitly-declared copy constructor for a class X will
2223 // have the form
2224 //
2225 // X::X(const X&)
2226 //
2227 // if
2228 bool HasConstCopyConstructor = true;
2229
2230 // -- each direct or virtual base class B of X has a copy
2231 // constructor whose first parameter is of type const B& or
2232 // const volatile B&, and
2233 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2234 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2235 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002236 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002237 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002238 = BaseClassDecl->hasConstCopyConstructor(Context);
2239 }
2240
2241 // -- for all the nonstatic data members of X that are of a
2242 // class type M (or array thereof), each such class type
2243 // has a copy constructor whose first parameter is of type
2244 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002245 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2246 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002247 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002248 QualType FieldType = (*Field)->getType();
2249 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2250 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002251 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002252 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002253 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002254 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002255 = FieldClassDecl->hasConstCopyConstructor(Context);
2256 }
2257 }
2258
Sebastian Redl64b45f72009-01-05 20:52:13 +00002259 // Otherwise, the implicitly declared copy constructor will have
2260 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002261 //
2262 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002263 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002264 if (HasConstCopyConstructor)
2265 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002266 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002267
Sebastian Redl64b45f72009-01-05 20:52:13 +00002268 // An implicitly-declared copy constructor is an inline public
2269 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002270 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002271 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002272 CXXConstructorDecl *CopyConstructor
2273 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002274 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002275 Context.getFunctionType(Context.VoidTy,
2276 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002277 false, 0,
2278 /*FIXME:*/false,
2279 false, 0, 0, false,
2280 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002281 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002282 /*isExplicit=*/false,
2283 /*isInline=*/true,
2284 /*isImplicitlyDeclared=*/true);
2285 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002286 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002287 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002288
2289 // Add the parameter to the constructor.
2290 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2291 ClassDecl->getLocation(),
2292 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002293 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002294 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002295 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002296 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002297 }
2298
Sebastian Redl64b45f72009-01-05 20:52:13 +00002299 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2300 // Note: The following rules are largely analoguous to the copy
2301 // constructor rules. Note that virtual bases are not taken into account
2302 // for determining the argument type of the operator. Note also that
2303 // operators taking an object instead of a reference are allowed.
2304 //
2305 // C++ [class.copy]p10:
2306 // If the class definition does not explicitly declare a copy
2307 // assignment operator, one is declared implicitly.
2308 // The implicitly-defined copy assignment operator for a class X
2309 // will have the form
2310 //
2311 // X& X::operator=(const X&)
2312 //
2313 // if
2314 bool HasConstCopyAssignment = true;
2315
2316 // -- each direct base class B of X has a copy assignment operator
2317 // whose parameter is of type const B&, const volatile B& or B,
2318 // and
2319 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2320 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002321 assert(!Base->getType()->isDependentType() &&
2322 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002323 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002324 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002325 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002326 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002327 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002328 }
2329
2330 // -- for all the nonstatic data members of X that are of a class
2331 // type M (or array thereof), each such class type has a copy
2332 // assignment operator whose parameter is of type const M&,
2333 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002334 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2335 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002336 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002337 QualType FieldType = (*Field)->getType();
2338 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2339 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002340 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002341 const CXXRecordDecl *FieldClassDecl
2342 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002343 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002344 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002345 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002346 }
2347 }
2348
2349 // Otherwise, the implicitly declared copy assignment operator will
2350 // have the form
2351 //
2352 // X& X::operator=(X&)
2353 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002354 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002355 if (HasConstCopyAssignment)
2356 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002357 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002358
2359 // An implicitly-declared copy assignment operator is an inline public
2360 // member of its class.
2361 DeclarationName Name =
2362 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2363 CXXMethodDecl *CopyAssignment =
2364 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2365 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002366 false, 0,
2367 /*FIXME:*/false,
2368 false, 0, 0, false,
2369 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002370 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002371 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002372 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002373 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002374 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002375
2376 // Add the parameter to the operator.
2377 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2378 ClassDecl->getLocation(),
2379 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002380 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002381 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002382 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002383
2384 // Don't call addedAssignmentOperator. There is no way to distinguish an
2385 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002386 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002387 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002388 }
2389
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002390 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002391 // C++ [class.dtor]p2:
2392 // If a class has no user-declared destructor, a destructor is
2393 // declared implicitly. An implicitly-declared destructor is an
2394 // inline public member of its class.
John McCall21ef0fa2010-03-11 09:03:00 +00002395 QualType Ty = Context.getFunctionType(Context.VoidTy,
2396 0, 0, false, 0,
2397 /*FIXME:*/false,
2398 false, 0, 0, false,
2399 CC_Default);
2400
Mike Stump1eb44332009-09-09 15:08:12 +00002401 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002402 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002403 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002404 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall21ef0fa2010-03-11 09:03:00 +00002405 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002406 /*isInline=*/true,
2407 /*isImplicitlyDeclared=*/true);
2408 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002409 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002410 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002411 ClassDecl->addDecl(Destructor);
John McCall21ef0fa2010-03-11 09:03:00 +00002412
2413 // This could be uniqued if it ever proves significant.
2414 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlssond5a942b2009-11-26 21:25:09 +00002415
2416 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002417 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002418}
2419
Douglas Gregor6569d682009-05-27 23:11:45 +00002420void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002421 Decl *D = TemplateD.getAs<Decl>();
2422 if (!D)
2423 return;
2424
2425 TemplateParameterList *Params = 0;
2426 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2427 Params = Template->getTemplateParameters();
2428 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2429 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2430 Params = PartialSpec->getTemplateParameters();
2431 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002432 return;
2433
Douglas Gregor6569d682009-05-27 23:11:45 +00002434 for (TemplateParameterList::iterator Param = Params->begin(),
2435 ParamEnd = Params->end();
2436 Param != ParamEnd; ++Param) {
2437 NamedDecl *Named = cast<NamedDecl>(*Param);
2438 if (Named->getDeclName()) {
2439 S->AddDecl(DeclPtrTy::make(Named));
2440 IdResolver.AddDecl(Named);
2441 }
2442 }
2443}
2444
John McCall7a1dc562009-12-19 10:49:29 +00002445void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2446 if (!RecordD) return;
2447 AdjustDeclIfTemplate(RecordD);
2448 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2449 PushDeclContext(S, Record);
2450}
2451
2452void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2453 if (!RecordD) return;
2454 PopDeclContext();
2455}
2456
Douglas Gregor72b505b2008-12-16 21:30:33 +00002457/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2458/// parsing a top-level (non-nested) C++ class, and we are now
2459/// parsing those parts of the given Method declaration that could
2460/// not be parsed earlier (C++ [class.mem]p2), such as default
2461/// arguments. This action should enter the scope of the given
2462/// Method declaration as if we had just parsed the qualified method
2463/// name. However, it should not bring the parameters into scope;
2464/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002465void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002466}
2467
2468/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2469/// C++ method declaration. We're (re-)introducing the given
2470/// function parameter into scope for use in parsing later parts of
2471/// the method declaration. For example, we could see an
2472/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002473void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002474 if (!ParamD)
2475 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Chris Lattnerb28317a2009-03-28 19:18:32 +00002477 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002478
2479 // If this parameter has an unparsed default argument, clear it out
2480 // to make way for the parsed default argument.
2481 if (Param->hasUnparsedDefaultArg())
2482 Param->setDefaultArg(0);
2483
Chris Lattnerb28317a2009-03-28 19:18:32 +00002484 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002485 if (Param->getDeclName())
2486 IdResolver.AddDecl(Param);
2487}
2488
2489/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2490/// processing the delayed method declaration for Method. The method
2491/// declaration is now considered finished. There may be a separate
2492/// ActOnStartOfFunctionDef action later (not necessarily
2493/// immediately!) for this method, if it was also defined inside the
2494/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002495void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002496 if (!MethodD)
2497 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002499 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Chris Lattnerb28317a2009-03-28 19:18:32 +00002501 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002502
2503 // Now that we have our default arguments, check the constructor
2504 // again. It could produce additional diagnostics or affect whether
2505 // the class has implicitly-declared destructors, among other
2506 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002507 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2508 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002509
2510 // Check the default arguments, which we may have added.
2511 if (!Method->isInvalidDecl())
2512 CheckCXXDefaultArguments(Method);
2513}
2514
Douglas Gregor42a552f2008-11-05 20:51:48 +00002515/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002516/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002517/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002518/// emit diagnostics and set the invalid bit to true. In any case, the type
2519/// will be updated to reflect a well-formed type for the constructor and
2520/// returned.
2521QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2522 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002523 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002524
2525 // C++ [class.ctor]p3:
2526 // A constructor shall not be virtual (10.3) or static (9.4). A
2527 // constructor can be invoked for a const, volatile or const
2528 // volatile object. A constructor shall not be declared const,
2529 // volatile, or const volatile (9.3.2).
2530 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002531 if (!D.isInvalidType())
2532 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2533 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2534 << SourceRange(D.getIdentifierLoc());
2535 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002536 }
2537 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002538 if (!D.isInvalidType())
2539 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2540 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2541 << SourceRange(D.getIdentifierLoc());
2542 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002543 SC = FunctionDecl::None;
2544 }
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Chris Lattner65401802009-04-25 08:28:21 +00002546 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2547 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002548 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002549 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2550 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002551 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002552 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2553 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002554 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002555 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2556 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002557 }
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregor42a552f2008-11-05 20:51:48 +00002559 // Rebuild the function type "R" without any type qualifiers (in
2560 // case any of the errors above fired) and with "void" as the
2561 // return type, since constructors don't have return types. We
2562 // *always* have to do this, because GetTypeForDeclarator will
2563 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002564 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002565 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2566 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002567 Proto->isVariadic(), 0,
2568 Proto->hasExceptionSpec(),
2569 Proto->hasAnyExceptionSpec(),
2570 Proto->getNumExceptions(),
2571 Proto->exception_begin(),
2572 Proto->getNoReturnAttr(),
2573 Proto->getCallConv());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002574}
2575
Douglas Gregor72b505b2008-12-16 21:30:33 +00002576/// CheckConstructor - Checks a fully-formed constructor for
2577/// well-formedness, issuing any diagnostics required. Returns true if
2578/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002579void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002580 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002581 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2582 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002583 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002584
2585 // C++ [class.copy]p3:
2586 // A declaration of a constructor for a class X is ill-formed if
2587 // its first parameter is of type (optionally cv-qualified) X and
2588 // either there are no other parameters or else all other
2589 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002590 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002591 ((Constructor->getNumParams() == 1) ||
2592 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002593 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2594 Constructor->getTemplateSpecializationKind()
2595 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002596 QualType ParamType = Constructor->getParamDecl(0)->getType();
2597 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2598 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002599 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2600 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002601 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002602
2603 // FIXME: Rather that making the constructor invalid, we should endeavor
2604 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002605 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002606 }
2607 }
Mike Stump1eb44332009-09-09 15:08:12 +00002608
Douglas Gregor72b505b2008-12-16 21:30:33 +00002609 // Notify the class that we've added a constructor.
2610 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002611}
2612
Anders Carlsson37909802009-11-30 21:24:50 +00002613/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2614/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002615bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002616 CXXRecordDecl *RD = Destructor->getParent();
2617
2618 if (Destructor->isVirtual()) {
2619 SourceLocation Loc;
2620
2621 if (!Destructor->isImplicit())
2622 Loc = Destructor->getLocation();
2623 else
2624 Loc = RD->getLocation();
2625
2626 // If we have a virtual destructor, look up the deallocation function
2627 FunctionDecl *OperatorDelete = 0;
2628 DeclarationName Name =
2629 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002630 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002631 return true;
2632
2633 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002634 }
Anders Carlsson37909802009-11-30 21:24:50 +00002635
2636 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002637}
2638
Mike Stump1eb44332009-09-09 15:08:12 +00002639static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002640FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2641 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2642 FTI.ArgInfo[0].Param &&
2643 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2644}
2645
Douglas Gregor42a552f2008-11-05 20:51:48 +00002646/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2647/// the well-formednes of the destructor declarator @p D with type @p
2648/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002649/// emit diagnostics and set the declarator to invalid. Even if this happens,
2650/// will be updated to reflect a well-formed type for the destructor and
2651/// returned.
2652QualType Sema::CheckDestructorDeclarator(Declarator &D,
2653 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002654 // C++ [class.dtor]p1:
2655 // [...] A typedef-name that names a class is a class-name
2656 // (7.1.3); however, a typedef-name that names a class shall not
2657 // be used as the identifier in the declarator for a destructor
2658 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002659 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002660 if (isa<TypedefType>(DeclaratorType)) {
2661 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002662 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002663 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002664 }
2665
2666 // C++ [class.dtor]p2:
2667 // A destructor is used to destroy objects of its class type. A
2668 // destructor takes no parameters, and no return type can be
2669 // specified for it (not even void). The address of a destructor
2670 // shall not be taken. A destructor shall not be static. A
2671 // destructor can be invoked for a const, volatile or const
2672 // volatile object. A destructor shall not be declared const,
2673 // volatile or const volatile (9.3.2).
2674 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002675 if (!D.isInvalidType())
2676 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2677 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2678 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002679 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002680 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002681 }
Chris Lattner65401802009-04-25 08:28:21 +00002682 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002683 // Destructors don't have return types, but the parser will
2684 // happily parse something like:
2685 //
2686 // class X {
2687 // float ~X();
2688 // };
2689 //
2690 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002691 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2692 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2693 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Chris Lattner65401802009-04-25 08:28:21 +00002696 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2697 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002698 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002699 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2700 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002701 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002702 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2703 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002704 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002705 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2706 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002707 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002708 }
2709
2710 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002711 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002712 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2713
2714 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002715 FTI.freeArgs();
2716 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002717 }
2718
Mike Stump1eb44332009-09-09 15:08:12 +00002719 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002720 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002721 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002722 D.setInvalidType();
2723 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002724
2725 // Rebuild the function type "R" without any type qualifiers or
2726 // parameters (in case any of the errors above fired) and with
2727 // "void" as the return type, since destructors don't have return
2728 // types. We *always* have to do this, because GetTypeForDeclarator
2729 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002730 // FIXME: Exceptions!
2731 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2732 false, false, 0, 0, false, CC_Default);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002733}
2734
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002735/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2736/// well-formednes of the conversion function declarator @p D with
2737/// type @p R. If there are any errors in the declarator, this routine
2738/// will emit diagnostics and return true. Otherwise, it will return
2739/// false. Either way, the type @p R will be updated to reflect a
2740/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002741void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002742 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002743 // C++ [class.conv.fct]p1:
2744 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002745 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002746 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002747 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002748 if (!D.isInvalidType())
2749 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2750 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2751 << SourceRange(D.getIdentifierLoc());
2752 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002753 SC = FunctionDecl::None;
2754 }
Chris Lattner6e475012009-04-25 08:35:12 +00002755 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002756 // Conversion functions don't have return types, but the parser will
2757 // happily parse something like:
2758 //
2759 // class X {
2760 // float operator bool();
2761 // };
2762 //
2763 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002764 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2765 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2766 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002767 }
2768
2769 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002770 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002771 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2772
2773 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002774 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002775 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002776 }
2777
Mike Stump1eb44332009-09-09 15:08:12 +00002778 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002779 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002780 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002781 D.setInvalidType();
2782 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002783
2784 // C++ [class.conv.fct]p4:
2785 // The conversion-type-id shall not represent a function type nor
2786 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002787 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002788 if (ConvType->isArrayType()) {
2789 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2790 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002791 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002792 } else if (ConvType->isFunctionType()) {
2793 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2794 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002795 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002796 }
2797
2798 // Rebuild the function type "R" without any parameters (in case any
2799 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002800 // return type.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002801 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002802 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002803 Proto->getTypeQuals(),
2804 Proto->hasExceptionSpec(),
2805 Proto->hasAnyExceptionSpec(),
2806 Proto->getNumExceptions(),
2807 Proto->exception_begin(),
2808 Proto->getNoReturnAttr(),
2809 Proto->getCallConv());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002810
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002811 // C++0x explicit conversion operators.
2812 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002813 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002814 diag::warn_explicit_conversion_functions)
2815 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002816}
2817
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002818/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2819/// the declaration of the given C++ conversion function. This routine
2820/// is responsible for recording the conversion function in the C++
2821/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002822Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002823 assert(Conversion && "Expected to receive a conversion function declaration");
2824
Douglas Gregor9d350972008-12-12 08:25:50 +00002825 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002826
2827 // Make sure we aren't redeclaring the conversion function.
2828 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002829
2830 // C++ [class.conv.fct]p1:
2831 // [...] A conversion function is never used to convert a
2832 // (possibly cv-qualified) object to the (possibly cv-qualified)
2833 // same object type (or a reference to it), to a (possibly
2834 // cv-qualified) base class of that type (or a reference to it),
2835 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002836 // FIXME: Suppress this warning if the conversion function ends up being a
2837 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002838 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002839 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002840 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002841 ConvType = ConvTypeRef->getPointeeType();
2842 if (ConvType->isRecordType()) {
2843 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2844 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002845 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002846 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002847 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002848 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002849 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002850 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002851 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002852 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002853 }
2854
Douglas Gregor48026d22010-01-11 18:40:55 +00002855 if (Conversion->getPrimaryTemplate()) {
2856 // ignore specializations
2857 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002858 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002859 = Conversion->getDescribedFunctionTemplate()) {
2860 if (ClassDecl->replaceConversion(
2861 ConversionTemplate->getPreviousDeclaration(),
2862 ConversionTemplate))
2863 return DeclPtrTy::make(ConversionTemplate);
2864 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2865 Conversion))
John McCallba135432009-11-21 08:51:07 +00002866 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002867 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002868 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002869 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002870 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002871 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002872 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002873
Chris Lattnerb28317a2009-03-28 19:18:32 +00002874 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002875}
2876
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002877//===----------------------------------------------------------------------===//
2878// Namespace Handling
2879//===----------------------------------------------------------------------===//
2880
2881/// ActOnStartNamespaceDef - This is called at the start of a namespace
2882/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002883Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2884 SourceLocation IdentLoc,
2885 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002886 SourceLocation LBrace,
2887 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002888 NamespaceDecl *Namespc =
2889 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2890 Namespc->setLBracLoc(LBrace);
2891
2892 Scope *DeclRegionScope = NamespcScope->getParent();
2893
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002894 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2895
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002896 if (II) {
2897 // C++ [namespace.def]p2:
2898 // The identifier in an original-namespace-definition shall not have been
2899 // previously defined in the declarative region in which the
2900 // original-namespace-definition appears. The identifier in an
2901 // original-namespace-definition is the name of the namespace. Subsequently
2902 // in that declarative region, it is treated as an original-namespace-name.
2903
John McCallf36e02d2009-10-09 21:13:30 +00002904 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002905 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002906 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Douglas Gregor44b43212008-12-11 16:49:14 +00002908 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2909 // This is an extended namespace definition.
2910 // Attach this namespace decl to the chain of extended namespace
2911 // definitions.
2912 OrigNS->setNextNamespace(Namespc);
2913 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002914
Mike Stump1eb44332009-09-09 15:08:12 +00002915 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002916 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002917 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002918 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002919 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002920 } else if (PrevDecl) {
2921 // This is an invalid name redefinition.
2922 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2923 << Namespc->getDeclName();
2924 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2925 Namespc->setInvalidDecl();
2926 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002927 } else if (II->isStr("std") &&
2928 CurContext->getLookupContext()->isTranslationUnit()) {
2929 // This is the first "real" definition of the namespace "std", so update
2930 // our cache of the "std" namespace to point at this definition.
2931 if (StdNamespace) {
2932 // We had already defined a dummy namespace "std". Link this new
2933 // namespace definition to the dummy namespace "std".
2934 StdNamespace->setNextNamespace(Namespc);
2935 StdNamespace->setLocation(IdentLoc);
2936 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2937 }
2938
2939 // Make our StdNamespace cache point at the first real definition of the
2940 // "std" namespace.
2941 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002942 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002943
2944 PushOnScopeChains(Namespc, DeclRegionScope);
2945 } else {
John McCall9aeed322009-10-01 00:25:31 +00002946 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002947 assert(Namespc->isAnonymousNamespace());
2948 CurContext->addDecl(Namespc);
2949
2950 // Link the anonymous namespace into its parent.
2951 NamespaceDecl *PrevDecl;
2952 DeclContext *Parent = CurContext->getLookupContext();
2953 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2954 PrevDecl = TU->getAnonymousNamespace();
2955 TU->setAnonymousNamespace(Namespc);
2956 } else {
2957 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2958 PrevDecl = ND->getAnonymousNamespace();
2959 ND->setAnonymousNamespace(Namespc);
2960 }
2961
2962 // Link the anonymous namespace with its previous declaration.
2963 if (PrevDecl) {
2964 assert(PrevDecl->isAnonymousNamespace());
2965 assert(!PrevDecl->getNextNamespace());
2966 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2967 PrevDecl->setNextNamespace(Namespc);
2968 }
John McCall9aeed322009-10-01 00:25:31 +00002969
2970 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2971 // behaves as if it were replaced by
2972 // namespace unique { /* empty body */ }
2973 // using namespace unique;
2974 // namespace unique { namespace-body }
2975 // where all occurrences of 'unique' in a translation unit are
2976 // replaced by the same identifier and this identifier differs
2977 // from all other identifiers in the entire program.
2978
2979 // We just create the namespace with an empty name and then add an
2980 // implicit using declaration, just like the standard suggests.
2981 //
2982 // CodeGen enforces the "universally unique" aspect by giving all
2983 // declarations semantically contained within an anonymous
2984 // namespace internal linkage.
2985
John McCall5fdd7642009-12-16 02:06:49 +00002986 if (!PrevDecl) {
2987 UsingDirectiveDecl* UD
2988 = UsingDirectiveDecl::Create(Context, CurContext,
2989 /* 'using' */ LBrace,
2990 /* 'namespace' */ SourceLocation(),
2991 /* qualifier */ SourceRange(),
2992 /* NNS */ NULL,
2993 /* identifier */ SourceLocation(),
2994 Namespc,
2995 /* Ancestor */ CurContext);
2996 UD->setImplicit();
2997 CurContext->addDecl(UD);
2998 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002999 }
3000
3001 // Although we could have an invalid decl (i.e. the namespace name is a
3002 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003003 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3004 // for the namespace has the declarations that showed up in that particular
3005 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003006 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003007 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003008}
3009
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003010/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3011/// is a namespace alias, returns the namespace it points to.
3012static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3013 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3014 return AD->getNamespace();
3015 return dyn_cast_or_null<NamespaceDecl>(D);
3016}
3017
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003018/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3019/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003020void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3021 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003022 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3023 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3024 Namespc->setRBracLoc(RBrace);
3025 PopDeclContext();
3026}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003027
Chris Lattnerb28317a2009-03-28 19:18:32 +00003028Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3029 SourceLocation UsingLoc,
3030 SourceLocation NamespcLoc,
3031 const CXXScopeSpec &SS,
3032 SourceLocation IdentLoc,
3033 IdentifierInfo *NamespcName,
3034 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003035 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3036 assert(NamespcName && "Invalid NamespcName.");
3037 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003038 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003039
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003040 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003041
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003042 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003043 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3044 LookupParsedName(R, S, &SS);
3045 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003046 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003047
John McCallf36e02d2009-10-09 21:13:30 +00003048 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003049 NamedDecl *Named = R.getFoundDecl();
3050 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3051 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003052 // C++ [namespace.udir]p1:
3053 // A using-directive specifies that the names in the nominated
3054 // namespace can be used in the scope in which the
3055 // using-directive appears after the using-directive. During
3056 // unqualified name lookup (3.4.1), the names appear as if they
3057 // were declared in the nearest enclosing namespace which
3058 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003059 // namespace. [Note: in this context, "contains" means "contains
3060 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003061
3062 // Find enclosing context containing both using-directive and
3063 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003064 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003065 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3066 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3067 CommonAncestor = CommonAncestor->getParent();
3068
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003069 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003070 SS.getRange(),
3071 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003072 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003073 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003074 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003075 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003076 }
3077
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003078 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003079 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003080 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003081}
3082
3083void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3084 // If scope has associated entity, then using directive is at namespace
3085 // or translation unit scope. We add UsingDirectiveDecls, into
3086 // it's lookup structure.
3087 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003088 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003089 else
3090 // Otherwise it is block-sope. using-directives will affect lookup
3091 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003092 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003093}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003094
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003095
3096Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003097 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003098 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003099 SourceLocation UsingLoc,
3100 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003101 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003102 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003103 bool IsTypeName,
3104 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003105 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Douglas Gregor12c118a2009-11-04 16:30:06 +00003107 switch (Name.getKind()) {
3108 case UnqualifiedId::IK_Identifier:
3109 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003110 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003111 case UnqualifiedId::IK_ConversionFunctionId:
3112 break;
3113
3114 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003115 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003116 // C++0x inherited constructors.
3117 if (getLangOptions().CPlusPlus0x) break;
3118
Douglas Gregor12c118a2009-11-04 16:30:06 +00003119 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3120 << SS.getRange();
3121 return DeclPtrTy();
3122
3123 case UnqualifiedId::IK_DestructorName:
3124 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3125 << SS.getRange();
3126 return DeclPtrTy();
3127
3128 case UnqualifiedId::IK_TemplateId:
3129 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3130 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3131 return DeclPtrTy();
3132 }
3133
3134 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003135 if (!TargetName)
3136 return DeclPtrTy();
3137
John McCall60fa3cf2009-12-11 02:10:03 +00003138 // Warn about using declarations.
3139 // TODO: store that the declaration was written without 'using' and
3140 // talk about access decls instead of using decls in the
3141 // diagnostics.
3142 if (!HasUsingKeyword) {
3143 UsingLoc = Name.getSourceRange().getBegin();
3144
3145 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3146 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3147 "using ");
3148 }
3149
John McCall9488ea12009-11-17 05:59:44 +00003150 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003151 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003152 TargetName, AttrList,
3153 /* IsInstantiation */ false,
3154 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003155 if (UD)
3156 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Anders Carlssonc72160b2009-08-28 05:40:36 +00003158 return DeclPtrTy::make(UD);
3159}
3160
John McCall9f54ad42009-12-10 09:41:52 +00003161/// Determines whether to create a using shadow decl for a particular
3162/// decl, given the set of decls existing prior to this using lookup.
3163bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3164 const LookupResult &Previous) {
3165 // Diagnose finding a decl which is not from a base class of the
3166 // current class. We do this now because there are cases where this
3167 // function will silently decide not to build a shadow decl, which
3168 // will pre-empt further diagnostics.
3169 //
3170 // We don't need to do this in C++0x because we do the check once on
3171 // the qualifier.
3172 //
3173 // FIXME: diagnose the following if we care enough:
3174 // struct A { int foo; };
3175 // struct B : A { using A::foo; };
3176 // template <class T> struct C : A {};
3177 // template <class T> struct D : C<T> { using B::foo; } // <---
3178 // This is invalid (during instantiation) in C++03 because B::foo
3179 // resolves to the using decl in B, which is not a base class of D<T>.
3180 // We can't diagnose it immediately because C<T> is an unknown
3181 // specialization. The UsingShadowDecl in D<T> then points directly
3182 // to A::foo, which will look well-formed when we instantiate.
3183 // The right solution is to not collapse the shadow-decl chain.
3184 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3185 DeclContext *OrigDC = Orig->getDeclContext();
3186
3187 // Handle enums and anonymous structs.
3188 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3189 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3190 while (OrigRec->isAnonymousStructOrUnion())
3191 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3192
3193 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3194 if (OrigDC == CurContext) {
3195 Diag(Using->getLocation(),
3196 diag::err_using_decl_nested_name_specifier_is_current_class)
3197 << Using->getNestedNameRange();
3198 Diag(Orig->getLocation(), diag::note_using_decl_target);
3199 return true;
3200 }
3201
3202 Diag(Using->getNestedNameRange().getBegin(),
3203 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3204 << Using->getTargetNestedNameDecl()
3205 << cast<CXXRecordDecl>(CurContext)
3206 << Using->getNestedNameRange();
3207 Diag(Orig->getLocation(), diag::note_using_decl_target);
3208 return true;
3209 }
3210 }
3211
3212 if (Previous.empty()) return false;
3213
3214 NamedDecl *Target = Orig;
3215 if (isa<UsingShadowDecl>(Target))
3216 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3217
John McCalld7533ec2009-12-11 02:33:26 +00003218 // If the target happens to be one of the previous declarations, we
3219 // don't have a conflict.
3220 //
3221 // FIXME: but we might be increasing its access, in which case we
3222 // should redeclare it.
3223 NamedDecl *NonTag = 0, *Tag = 0;
3224 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3225 I != E; ++I) {
3226 NamedDecl *D = (*I)->getUnderlyingDecl();
3227 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3228 return false;
3229
3230 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3231 }
3232
John McCall9f54ad42009-12-10 09:41:52 +00003233 if (Target->isFunctionOrFunctionTemplate()) {
3234 FunctionDecl *FD;
3235 if (isa<FunctionTemplateDecl>(Target))
3236 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3237 else
3238 FD = cast<FunctionDecl>(Target);
3239
3240 NamedDecl *OldDecl = 0;
3241 switch (CheckOverload(FD, Previous, OldDecl)) {
3242 case Ovl_Overload:
3243 return false;
3244
3245 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003246 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003247 break;
3248
3249 // We found a decl with the exact signature.
3250 case Ovl_Match:
3251 if (isa<UsingShadowDecl>(OldDecl)) {
3252 // Silently ignore the possible conflict.
3253 return false;
3254 }
3255
3256 // If we're in a record, we want to hide the target, so we
3257 // return true (without a diagnostic) to tell the caller not to
3258 // build a shadow decl.
3259 if (CurContext->isRecord())
3260 return true;
3261
3262 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003263 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003264 break;
3265 }
3266
3267 Diag(Target->getLocation(), diag::note_using_decl_target);
3268 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3269 return true;
3270 }
3271
3272 // Target is not a function.
3273
John McCall9f54ad42009-12-10 09:41:52 +00003274 if (isa<TagDecl>(Target)) {
3275 // No conflict between a tag and a non-tag.
3276 if (!Tag) return false;
3277
John McCall41ce66f2009-12-10 19:51:03 +00003278 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003279 Diag(Target->getLocation(), diag::note_using_decl_target);
3280 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3281 return true;
3282 }
3283
3284 // No conflict between a tag and a non-tag.
3285 if (!NonTag) return false;
3286
John McCall41ce66f2009-12-10 19:51:03 +00003287 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003288 Diag(Target->getLocation(), diag::note_using_decl_target);
3289 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3290 return true;
3291}
3292
John McCall9488ea12009-11-17 05:59:44 +00003293/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003294UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003295 UsingDecl *UD,
3296 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003297
3298 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003299 NamedDecl *Target = Orig;
3300 if (isa<UsingShadowDecl>(Target)) {
3301 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3302 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003303 }
3304
3305 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003306 = UsingShadowDecl::Create(Context, CurContext,
3307 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003308 UD->addShadowDecl(Shadow);
3309
3310 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003311 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003312 else
John McCall604e7f12009-12-08 07:46:18 +00003313 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003314 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003315
John McCall604e7f12009-12-08 07:46:18 +00003316 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3317 Shadow->setInvalidDecl();
3318
John McCall9f54ad42009-12-10 09:41:52 +00003319 return Shadow;
3320}
John McCall604e7f12009-12-08 07:46:18 +00003321
John McCall9f54ad42009-12-10 09:41:52 +00003322/// Hides a using shadow declaration. This is required by the current
3323/// using-decl implementation when a resolvable using declaration in a
3324/// class is followed by a declaration which would hide or override
3325/// one or more of the using decl's targets; for example:
3326///
3327/// struct Base { void foo(int); };
3328/// struct Derived : Base {
3329/// using Base::foo;
3330/// void foo(int);
3331/// };
3332///
3333/// The governing language is C++03 [namespace.udecl]p12:
3334///
3335/// When a using-declaration brings names from a base class into a
3336/// derived class scope, member functions in the derived class
3337/// override and/or hide member functions with the same name and
3338/// parameter types in a base class (rather than conflicting).
3339///
3340/// There are two ways to implement this:
3341/// (1) optimistically create shadow decls when they're not hidden
3342/// by existing declarations, or
3343/// (2) don't create any shadow decls (or at least don't make them
3344/// visible) until we've fully parsed/instantiated the class.
3345/// The problem with (1) is that we might have to retroactively remove
3346/// a shadow decl, which requires several O(n) operations because the
3347/// decl structures are (very reasonably) not designed for removal.
3348/// (2) avoids this but is very fiddly and phase-dependent.
3349void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3350 // Remove it from the DeclContext...
3351 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003352
John McCall9f54ad42009-12-10 09:41:52 +00003353 // ...and the scope, if applicable...
3354 if (S) {
3355 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3356 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003357 }
3358
John McCall9f54ad42009-12-10 09:41:52 +00003359 // ...and the using decl.
3360 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3361
3362 // TODO: complain somehow if Shadow was used. It shouldn't
3363 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003364}
3365
John McCall7ba107a2009-11-18 02:36:19 +00003366/// Builds a using declaration.
3367///
3368/// \param IsInstantiation - Whether this call arises from an
3369/// instantiation of an unresolved using declaration. We treat
3370/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003371NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3372 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003373 const CXXScopeSpec &SS,
3374 SourceLocation IdentLoc,
3375 DeclarationName Name,
3376 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003377 bool IsInstantiation,
3378 bool IsTypeName,
3379 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003380 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3381 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003382
Anders Carlsson550b14b2009-08-28 05:49:21 +00003383 // FIXME: We ignore attributes for now.
3384 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003386 if (SS.isEmpty()) {
3387 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003388 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003389 }
Mike Stump1eb44332009-09-09 15:08:12 +00003390
John McCall9f54ad42009-12-10 09:41:52 +00003391 // Do the redeclaration lookup in the current scope.
3392 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3393 ForRedeclaration);
3394 Previous.setHideTags(false);
3395 if (S) {
3396 LookupName(Previous, S);
3397
3398 // It is really dumb that we have to do this.
3399 LookupResult::Filter F = Previous.makeFilter();
3400 while (F.hasNext()) {
3401 NamedDecl *D = F.next();
3402 if (!isDeclInScope(D, CurContext, S))
3403 F.erase();
3404 }
3405 F.done();
3406 } else {
3407 assert(IsInstantiation && "no scope in non-instantiation");
3408 assert(CurContext->isRecord() && "scope not record in instantiation");
3409 LookupQualifiedName(Previous, CurContext);
3410 }
3411
Mike Stump1eb44332009-09-09 15:08:12 +00003412 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003413 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3414
John McCall9f54ad42009-12-10 09:41:52 +00003415 // Check for invalid redeclarations.
3416 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3417 return 0;
3418
3419 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003420 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3421 return 0;
3422
John McCallaf8e6ed2009-11-12 03:15:40 +00003423 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003424 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003425 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003426 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003427 // FIXME: not all declaration name kinds are legal here
3428 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3429 UsingLoc, TypenameLoc,
3430 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003431 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003432 } else {
3433 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3434 UsingLoc, SS.getRange(), NNS,
3435 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003436 }
John McCalled976492009-12-04 22:46:56 +00003437 } else {
3438 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3439 SS.getRange(), UsingLoc, NNS, Name,
3440 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003441 }
John McCalled976492009-12-04 22:46:56 +00003442 D->setAccess(AS);
3443 CurContext->addDecl(D);
3444
3445 if (!LookupContext) return D;
3446 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003447
John McCall604e7f12009-12-08 07:46:18 +00003448 if (RequireCompleteDeclContext(SS)) {
3449 UD->setInvalidDecl();
3450 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003451 }
3452
John McCall604e7f12009-12-08 07:46:18 +00003453 // Look up the target name.
3454
John McCalla24dc2e2009-11-17 02:14:36 +00003455 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003456
John McCall604e7f12009-12-08 07:46:18 +00003457 // Unlike most lookups, we don't always want to hide tag
3458 // declarations: tag names are visible through the using declaration
3459 // even if hidden by ordinary names, *except* in a dependent context
3460 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003461 if (!IsInstantiation)
3462 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003463
John McCalla24dc2e2009-11-17 02:14:36 +00003464 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003465
John McCallf36e02d2009-10-09 21:13:30 +00003466 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003467 Diag(IdentLoc, diag::err_no_member)
3468 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003469 UD->setInvalidDecl();
3470 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003471 }
3472
John McCalled976492009-12-04 22:46:56 +00003473 if (R.isAmbiguous()) {
3474 UD->setInvalidDecl();
3475 return UD;
3476 }
Mike Stump1eb44332009-09-09 15:08:12 +00003477
John McCall7ba107a2009-11-18 02:36:19 +00003478 if (IsTypeName) {
3479 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003480 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003481 Diag(IdentLoc, diag::err_using_typename_non_type);
3482 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3483 Diag((*I)->getUnderlyingDecl()->getLocation(),
3484 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003485 UD->setInvalidDecl();
3486 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003487 }
3488 } else {
3489 // If we asked for a non-typename and we got a type, error out,
3490 // but only if this is an instantiation of an unresolved using
3491 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003492 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003493 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3494 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003495 UD->setInvalidDecl();
3496 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003497 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003498 }
3499
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003500 // C++0x N2914 [namespace.udecl]p6:
3501 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003502 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003503 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3504 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003505 UD->setInvalidDecl();
3506 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003507 }
Mike Stump1eb44332009-09-09 15:08:12 +00003508
John McCall9f54ad42009-12-10 09:41:52 +00003509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3510 if (!CheckUsingShadowDecl(UD, *I, Previous))
3511 BuildUsingShadowDecl(S, UD, *I);
3512 }
John McCall9488ea12009-11-17 05:59:44 +00003513
3514 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003515}
3516
John McCall9f54ad42009-12-10 09:41:52 +00003517/// Checks that the given using declaration is not an invalid
3518/// redeclaration. Note that this is checking only for the using decl
3519/// itself, not for any ill-formedness among the UsingShadowDecls.
3520bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3521 bool isTypeName,
3522 const CXXScopeSpec &SS,
3523 SourceLocation NameLoc,
3524 const LookupResult &Prev) {
3525 // C++03 [namespace.udecl]p8:
3526 // C++0x [namespace.udecl]p10:
3527 // A using-declaration is a declaration and can therefore be used
3528 // repeatedly where (and only where) multiple declarations are
3529 // allowed.
3530 // That's only in file contexts.
3531 if (CurContext->getLookupContext()->isFileContext())
3532 return false;
3533
3534 NestedNameSpecifier *Qual
3535 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3536
3537 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3538 NamedDecl *D = *I;
3539
3540 bool DTypename;
3541 NestedNameSpecifier *DQual;
3542 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3543 DTypename = UD->isTypeName();
3544 DQual = UD->getTargetNestedNameDecl();
3545 } else if (UnresolvedUsingValueDecl *UD
3546 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3547 DTypename = false;
3548 DQual = UD->getTargetNestedNameSpecifier();
3549 } else if (UnresolvedUsingTypenameDecl *UD
3550 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3551 DTypename = true;
3552 DQual = UD->getTargetNestedNameSpecifier();
3553 } else continue;
3554
3555 // using decls differ if one says 'typename' and the other doesn't.
3556 // FIXME: non-dependent using decls?
3557 if (isTypeName != DTypename) continue;
3558
3559 // using decls differ if they name different scopes (but note that
3560 // template instantiation can cause this check to trigger when it
3561 // didn't before instantiation).
3562 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3563 Context.getCanonicalNestedNameSpecifier(DQual))
3564 continue;
3565
3566 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003567 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003568 return true;
3569 }
3570
3571 return false;
3572}
3573
John McCall604e7f12009-12-08 07:46:18 +00003574
John McCalled976492009-12-04 22:46:56 +00003575/// Checks that the given nested-name qualifier used in a using decl
3576/// in the current context is appropriately related to the current
3577/// scope. If an error is found, diagnoses it and returns true.
3578bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3579 const CXXScopeSpec &SS,
3580 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003581 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003582
John McCall604e7f12009-12-08 07:46:18 +00003583 if (!CurContext->isRecord()) {
3584 // C++03 [namespace.udecl]p3:
3585 // C++0x [namespace.udecl]p8:
3586 // A using-declaration for a class member shall be a member-declaration.
3587
3588 // If we weren't able to compute a valid scope, it must be a
3589 // dependent class scope.
3590 if (!NamedContext || NamedContext->isRecord()) {
3591 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3592 << SS.getRange();
3593 return true;
3594 }
3595
3596 // Otherwise, everything is known to be fine.
3597 return false;
3598 }
3599
3600 // The current scope is a record.
3601
3602 // If the named context is dependent, we can't decide much.
3603 if (!NamedContext) {
3604 // FIXME: in C++0x, we can diagnose if we can prove that the
3605 // nested-name-specifier does not refer to a base class, which is
3606 // still possible in some cases.
3607
3608 // Otherwise we have to conservatively report that things might be
3609 // okay.
3610 return false;
3611 }
3612
3613 if (!NamedContext->isRecord()) {
3614 // Ideally this would point at the last name in the specifier,
3615 // but we don't have that level of source info.
3616 Diag(SS.getRange().getBegin(),
3617 diag::err_using_decl_nested_name_specifier_is_not_class)
3618 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3619 return true;
3620 }
3621
3622 if (getLangOptions().CPlusPlus0x) {
3623 // C++0x [namespace.udecl]p3:
3624 // In a using-declaration used as a member-declaration, the
3625 // nested-name-specifier shall name a base class of the class
3626 // being defined.
3627
3628 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3629 cast<CXXRecordDecl>(NamedContext))) {
3630 if (CurContext == NamedContext) {
3631 Diag(NameLoc,
3632 diag::err_using_decl_nested_name_specifier_is_current_class)
3633 << SS.getRange();
3634 return true;
3635 }
3636
3637 Diag(SS.getRange().getBegin(),
3638 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3639 << (NestedNameSpecifier*) SS.getScopeRep()
3640 << cast<CXXRecordDecl>(CurContext)
3641 << SS.getRange();
3642 return true;
3643 }
3644
3645 return false;
3646 }
3647
3648 // C++03 [namespace.udecl]p4:
3649 // A using-declaration used as a member-declaration shall refer
3650 // to a member of a base class of the class being defined [etc.].
3651
3652 // Salient point: SS doesn't have to name a base class as long as
3653 // lookup only finds members from base classes. Therefore we can
3654 // diagnose here only if we can prove that that can't happen,
3655 // i.e. if the class hierarchies provably don't intersect.
3656
3657 // TODO: it would be nice if "definitely valid" results were cached
3658 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3659 // need to be repeated.
3660
3661 struct UserData {
3662 llvm::DenseSet<const CXXRecordDecl*> Bases;
3663
3664 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3665 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3666 Data->Bases.insert(Base);
3667 return true;
3668 }
3669
3670 bool hasDependentBases(const CXXRecordDecl *Class) {
3671 return !Class->forallBases(collect, this);
3672 }
3673
3674 /// Returns true if the base is dependent or is one of the
3675 /// accumulated base classes.
3676 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3677 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3678 return !Data->Bases.count(Base);
3679 }
3680
3681 bool mightShareBases(const CXXRecordDecl *Class) {
3682 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3683 }
3684 };
3685
3686 UserData Data;
3687
3688 // Returns false if we find a dependent base.
3689 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3690 return false;
3691
3692 // Returns false if the class has a dependent base or if it or one
3693 // of its bases is present in the base set of the current context.
3694 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3695 return false;
3696
3697 Diag(SS.getRange().getBegin(),
3698 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3699 << (NestedNameSpecifier*) SS.getScopeRep()
3700 << cast<CXXRecordDecl>(CurContext)
3701 << SS.getRange();
3702
3703 return true;
John McCalled976492009-12-04 22:46:56 +00003704}
3705
Mike Stump1eb44332009-09-09 15:08:12 +00003706Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003707 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003708 SourceLocation AliasLoc,
3709 IdentifierInfo *Alias,
3710 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003711 SourceLocation IdentLoc,
3712 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Anders Carlsson81c85c42009-03-28 23:53:49 +00003714 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003715 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3716 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003717
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003718 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003719 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003720 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003721 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003722 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003723 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003724 if (!R.isAmbiguous() && !R.empty() &&
3725 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003726 return DeclPtrTy();
3727 }
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003729 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3730 diag::err_redefinition_different_kind;
3731 Diag(AliasLoc, DiagID) << Alias;
3732 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003733 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003734 }
3735
John McCalla24dc2e2009-11-17 02:14:36 +00003736 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003737 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003738
John McCallf36e02d2009-10-09 21:13:30 +00003739 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003740 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003741 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003742 }
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003744 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003745 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3746 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003747 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003748 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003749
John McCall3dbd3d52010-02-16 06:53:13 +00003750 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00003751 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003752}
3753
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003754void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3755 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003756 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3757 !Constructor->isUsed()) &&
3758 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Eli Friedman80c30da2009-11-09 19:20:36 +00003760 CXXRecordDecl *ClassDecl
3761 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3762 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003763
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003764 DeclContext *PreviousContext = CurContext;
3765 CurContext = Constructor;
3766 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003767 Diag(CurrentLocation, diag::note_member_synthesized_at)
3768 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003769 Constructor->setInvalidDecl();
3770 } else {
3771 Constructor->setUsed();
3772 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003773 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003774}
3775
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003776void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003777 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003778 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3779 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003780 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003781 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003782
3783 DeclContext *PreviousContext = CurContext;
3784 CurContext = Destructor;
3785
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003786 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003787 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003788 // implicitly defined, all the implicitly-declared default destructors
3789 // for its base class and its non-static data members shall have been
3790 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003791 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3792 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003793 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003794 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003795 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003796 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003797 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3798 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3799 else
Mike Stump1eb44332009-09-09 15:08:12 +00003800 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003801 "DefineImplicitDestructor - missing dtor in a base class");
3802 }
3803 }
Mike Stump1eb44332009-09-09 15:08:12 +00003804
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003805 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3806 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003807 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3808 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3809 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003810 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003811 CXXRecordDecl *FieldClassDecl
3812 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3813 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003814 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003815 const_cast<CXXDestructorDecl*>(
3816 FieldClassDecl->getDestructor(Context)))
3817 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3818 else
Mike Stump1eb44332009-09-09 15:08:12 +00003819 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003820 "DefineImplicitDestructor - missing dtor in class of a data member");
3821 }
3822 }
3823 }
Anders Carlsson37909802009-11-30 21:24:50 +00003824
3825 // FIXME: If CheckDestructor fails, we should emit a note about where the
3826 // implicit destructor was needed.
3827 if (CheckDestructor(Destructor)) {
3828 Diag(CurrentLocation, diag::note_member_synthesized_at)
3829 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3830
3831 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003832 CurContext = PreviousContext;
3833
Anders Carlsson37909802009-11-30 21:24:50 +00003834 return;
3835 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003836 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003837
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003838 Destructor->setUsed();
3839}
3840
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003841void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3842 CXXMethodDecl *MethodDecl) {
3843 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3844 MethodDecl->getOverloadedOperator() == OO_Equal &&
3845 !MethodDecl->isUsed()) &&
3846 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003848 CXXRecordDecl *ClassDecl
3849 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003851 DeclContext *PreviousContext = CurContext;
3852 CurContext = MethodDecl;
3853
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003854 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003855 // Before the implicitly-declared copy assignment operator for a class is
3856 // implicitly defined, all implicitly-declared copy assignment operators
3857 // for its direct base classes and its nonstatic data members shall have
3858 // been implicitly defined.
3859 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003860 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3861 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003862 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003863 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003864 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003865 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3866 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003867 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3868 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003869 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3870 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003871 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3872 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3873 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003874 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003875 CXXRecordDecl *FieldClassDecl
3876 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003877 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003878 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3879 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003880 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003881 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003882 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003883 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3884 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003885 Diag(CurrentLocation, diag::note_first_required_here);
3886 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003887 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003888 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003889 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3890 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003891 Diag(CurrentLocation, diag::note_first_required_here);
3892 err = true;
3893 }
3894 }
3895 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003896 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003897
3898 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003899}
3900
3901CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003902Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3903 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003904 CXXRecordDecl *ClassDecl) {
3905 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3906 QualType RHSType(LHSType);
3907 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003908 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003909 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003910 RHSType = Context.getCVRQualifiedType(RHSType,
3911 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003912 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003913 LHSType,
3914 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003915 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003916 RHSType,
3917 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003918 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003919 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003920 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003921 CandidateSet);
3922 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003923 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003924 return cast<CXXMethodDecl>(Best->Function);
3925 assert(false &&
3926 "getAssignOperatorMethod - copy assignment operator method not found");
3927 return 0;
3928}
3929
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003930void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3931 CXXConstructorDecl *CopyConstructor,
3932 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003933 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003934 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003935 !CopyConstructor->isUsed()) &&
3936 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003938 CXXRecordDecl *ClassDecl
3939 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3940 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003941
3942 DeclContext *PreviousContext = CurContext;
3943 CurContext = CopyConstructor;
3944
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003945 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003946 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003947 // implicitly defined, all the implicitly-declared copy constructors
3948 // for its base class and its non-static data members shall have been
3949 // implicitly defined.
3950 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3951 Base != ClassDecl->bases_end(); ++Base) {
3952 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003953 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003954 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003955 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003956 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003957 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003958 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3959 FieldEnd = ClassDecl->field_end();
3960 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003961 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3962 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3963 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003964 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003965 CXXRecordDecl *FieldClassDecl
3966 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003967 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003968 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003969 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003970 }
3971 }
3972 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003973
3974 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003975}
3976
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003977Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003978Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003979 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003980 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003981 bool RequiresZeroInit,
3982 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003983 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Douglas Gregor39da0b82009-09-09 23:08:42 +00003985 // C++ [class.copy]p15:
3986 // Whenever a temporary class object is copied using a copy constructor, and
3987 // this object and the copy have the same cv-unqualified type, an
3988 // implementation is permitted to treat the original and the copy as two
3989 // different ways of referring to the same object and not perform a copy at
3990 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003991
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003992 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003993 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003994 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003995 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3996 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3997 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003998 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3999 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004000 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
4001 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004002 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4003 if (ICE->getCastKind() == CastExpr::CK_NoOp)
4004 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00004005
4006 if (CallExpr *CE = dyn_cast<CallExpr>(E))
4007 Elidable = !CE->getCallReturnType()->isReferenceType();
4008 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004009 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00004010 else if (isa<CXXConstructExpr>(E))
4011 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004012 }
Mike Stump1eb44332009-09-09 15:08:12 +00004013
4014 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004015 Elidable, move(ExprArgs), RequiresZeroInit,
4016 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004017}
4018
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004019/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4020/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004021Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004022Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4023 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004024 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004025 bool RequiresZeroInit,
4026 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004027 unsigned NumExprs = ExprArgs.size();
4028 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Douglas Gregor7edfb692009-11-23 12:27:39 +00004030 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004031 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004032 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004033 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004034}
4035
Mike Stump1eb44332009-09-09 15:08:12 +00004036bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004037 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004038 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004039 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004040 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004041 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004042 if (TempResult.isInvalid())
4043 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004045 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004046 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004047 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004048 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Anders Carlssonfe2de492009-08-25 05:18:00 +00004050 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004051}
4052
John McCall68c6c9a2010-02-02 09:10:11 +00004053void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4054 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004055 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4056 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004057 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4058 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004059 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004060 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004061}
4062
Mike Stump1eb44332009-09-09 15:08:12 +00004063/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004064/// ActOnDeclarator, when a C++ direct initializer is present.
4065/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004066void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4067 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004068 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004069 SourceLocation *CommaLocs,
4070 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004071 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004072 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004073
4074 // If there is no declaration, there was an error parsing it. Just ignore
4075 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004076 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004077 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004078
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004079 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4080 if (!VDecl) {
4081 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4082 RealDecl->setInvalidDecl();
4083 return;
4084 }
4085
Douglas Gregor83ddad32009-08-26 21:14:46 +00004086 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004087 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004088 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4089 //
4090 // Clients that want to distinguish between the two forms, can check for
4091 // direct initializer using VarDecl::hasCXXDirectInitializer().
4092 // A major benefit is that clients that don't particularly care about which
4093 // exactly form was it (like the CodeGen) can handle both cases without
4094 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004095
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004096 // C++ 8.5p11:
4097 // The form of initialization (using parentheses or '=') is generally
4098 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004099 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004100 QualType DeclInitType = VDecl->getType();
4101 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004102 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004103
Douglas Gregor4dffad62010-02-11 22:55:30 +00004104 if (!VDecl->getType()->isDependentType() &&
4105 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004106 diag::err_typecheck_decl_incomplete_type)) {
4107 VDecl->setInvalidDecl();
4108 return;
4109 }
4110
Douglas Gregor90f93822009-12-22 22:17:25 +00004111 // The variable can not have an abstract class type.
4112 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4113 diag::err_abstract_type_in_decl,
4114 AbstractVariableType))
4115 VDecl->setInvalidDecl();
4116
Sebastian Redl31310a22010-02-01 20:16:42 +00004117 const VarDecl *Def;
4118 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004119 Diag(VDecl->getLocation(), diag::err_redefinition)
4120 << VDecl->getDeclName();
4121 Diag(Def->getLocation(), diag::note_previous_definition);
4122 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004123 return;
4124 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004125
4126 // If either the declaration has a dependent type or if any of the
4127 // expressions is type-dependent, we represent the initialization
4128 // via a ParenListExpr for later use during template instantiation.
4129 if (VDecl->getType()->isDependentType() ||
4130 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4131 // Let clients know that initialization was done with a direct initializer.
4132 VDecl->setCXXDirectInitializer(true);
4133
4134 // Store the initialization expressions as a ParenListExpr.
4135 unsigned NumExprs = Exprs.size();
4136 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4137 (Expr **)Exprs.release(),
4138 NumExprs, RParenLoc));
4139 return;
4140 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004141
4142 // Capture the variable that is being initialized and the style of
4143 // initialization.
4144 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4145
4146 // FIXME: Poor source location information.
4147 InitializationKind Kind
4148 = InitializationKind::CreateDirect(VDecl->getLocation(),
4149 LParenLoc, RParenLoc);
4150
4151 InitializationSequence InitSeq(*this, Entity, Kind,
4152 (Expr**)Exprs.get(), Exprs.size());
4153 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4154 if (Result.isInvalid()) {
4155 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004156 return;
4157 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004158
4159 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004160 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004161 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004162
John McCall68c6c9a2010-02-02 09:10:11 +00004163 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4164 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004165}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004166
Douglas Gregor19aeac62009-11-14 03:27:21 +00004167/// \brief Add the applicable constructor candidates for an initialization
4168/// by constructor.
4169static void AddConstructorInitializationCandidates(Sema &SemaRef,
4170 QualType ClassType,
4171 Expr **Args,
4172 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004173 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004174 OverloadCandidateSet &CandidateSet) {
4175 // C++ [dcl.init]p14:
4176 // If the initialization is direct-initialization, or if it is
4177 // copy-initialization where the cv-unqualified version of the
4178 // source type is the same class as, or a derived class of, the
4179 // class of the destination, constructors are considered. The
4180 // applicable constructors are enumerated (13.3.1.3), and the
4181 // best one is chosen through overload resolution (13.3). The
4182 // constructor so selected is called to initialize the object,
4183 // with the initializer expression(s) as its argument(s). If no
4184 // constructor applies, or the overload resolution is ambiguous,
4185 // the initialization is ill-formed.
4186 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4187 assert(ClassRec && "Can only initialize a class type here");
4188
4189 // FIXME: When we decide not to synthesize the implicitly-declared
4190 // constructors, we'll need to make them appear here.
4191
4192 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4193 DeclarationName ConstructorName
4194 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4195 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4196 DeclContext::lookup_const_iterator Con, ConEnd;
4197 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4198 Con != ConEnd; ++Con) {
4199 // Find the constructor (which may be a template).
4200 CXXConstructorDecl *Constructor = 0;
4201 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4202 if (ConstructorTmpl)
4203 Constructor
4204 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4205 else
4206 Constructor = cast<CXXConstructorDecl>(*Con);
4207
Douglas Gregor20093b42009-12-09 23:02:17 +00004208 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4209 (Kind.getKind() == InitializationKind::IK_Value) ||
4210 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004211 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004212 ((Kind.getKind() == InitializationKind::IK_Default) &&
4213 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004214 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004215 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004216 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004217 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004218 Args, NumArgs, CandidateSet);
4219 else
John McCall86820f52010-01-26 01:37:31 +00004220 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4221 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004222 }
4223 }
4224}
4225
4226/// \brief Attempt to perform initialization by constructor
4227/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4228/// copy-initialization.
4229///
4230/// This routine determines whether initialization by constructor is possible,
4231/// but it does not emit any diagnostics in the case where the initialization
4232/// is ill-formed.
4233///
4234/// \param ClassType the type of the object being initialized, which must have
4235/// class type.
4236///
4237/// \param Args the arguments provided to initialize the object
4238///
4239/// \param NumArgs the number of arguments provided to initialize the object
4240///
4241/// \param Kind the type of initialization being performed
4242///
4243/// \returns the constructor used to initialize the object, if successful.
4244/// Otherwise, emits a diagnostic and returns NULL.
4245CXXConstructorDecl *
4246Sema::TryInitializationByConstructor(QualType ClassType,
4247 Expr **Args, unsigned NumArgs,
4248 SourceLocation Loc,
4249 InitializationKind Kind) {
4250 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004251 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004252 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4253 CandidateSet);
4254
4255 // Determine whether we found a constructor we can use.
4256 OverloadCandidateSet::iterator Best;
4257 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4258 case OR_Success:
4259 case OR_Deleted:
4260 // We found a constructor. Return it.
4261 return cast<CXXConstructorDecl>(Best->Function);
4262
4263 case OR_No_Viable_Function:
4264 case OR_Ambiguous:
4265 // Overload resolution failed. Return nothing.
4266 return 0;
4267 }
4268
4269 // Silence GCC warning
4270 return 0;
4271}
4272
Douglas Gregor39da0b82009-09-09 23:08:42 +00004273/// \brief Given a constructor and the set of arguments provided for the
4274/// constructor, convert the arguments and add any required default arguments
4275/// to form a proper call to this constructor.
4276///
4277/// \returns true if an error occurred, false otherwise.
4278bool
4279Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4280 MultiExprArg ArgsPtr,
4281 SourceLocation Loc,
4282 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4283 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4284 unsigned NumArgs = ArgsPtr.size();
4285 Expr **Args = (Expr **)ArgsPtr.get();
4286
4287 const FunctionProtoType *Proto
4288 = Constructor->getType()->getAs<FunctionProtoType>();
4289 assert(Proto && "Constructor without a prototype?");
4290 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004291
4292 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004293 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004294 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004295 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004296 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004297
4298 VariadicCallType CallType =
4299 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4300 llvm::SmallVector<Expr *, 8> AllArgs;
4301 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4302 Proto, 0, Args, NumArgs, AllArgs,
4303 CallType);
4304 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4305 ConvertedArgs.push_back(AllArgs[i]);
4306 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004307}
4308
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004309/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4310/// determine whether they are reference-related,
4311/// reference-compatible, reference-compatible with added
4312/// qualification, or incompatible, for use in C++ initialization by
4313/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4314/// type, and the first type (T1) is the pointee type of the reference
4315/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004316Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004317Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004318 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004319 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004320 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004321 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004322 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004323
Douglas Gregor393896f2009-11-05 13:06:35 +00004324 QualType T1 = Context.getCanonicalType(OrigT1);
4325 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004326 Qualifiers T1Quals, T2Quals;
4327 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4328 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004329
4330 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004331 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004332 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004333 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004334 if (UnqualT1 == UnqualT2)
4335 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004336 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4337 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4338 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004339 DerivedToBase = true;
4340 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004341 return Ref_Incompatible;
4342
4343 // At this point, we know that T1 and T2 are reference-related (at
4344 // least).
4345
Chandler Carruth28e318c2009-12-29 07:16:59 +00004346 // If the type is an array type, promote the element qualifiers to the type
4347 // for comparison.
4348 if (isa<ArrayType>(T1) && T1Quals)
4349 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4350 if (isa<ArrayType>(T2) && T2Quals)
4351 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4352
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004353 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004354 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004355 // reference-related to T2 and cv1 is the same cv-qualification
4356 // as, or greater cv-qualification than, cv2. For purposes of
4357 // overload resolution, cases for which cv1 is greater
4358 // cv-qualification than cv2 are identified as
4359 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004360 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004361 return Ref_Compatible;
4362 else if (T1.isMoreQualifiedThan(T2))
4363 return Ref_Compatible_With_Added_Qualification;
4364 else
4365 return Ref_Related;
4366}
4367
4368/// CheckReferenceInit - Check the initialization of a reference
4369/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4370/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004371/// list), and DeclType is the type of the declaration. When ICS is
4372/// non-null, this routine will compute the implicit conversion
4373/// sequence according to C++ [over.ics.ref] and will not produce any
4374/// diagnostics; when ICS is null, it will emit diagnostics when any
4375/// errors are found. Either way, a return value of true indicates
4376/// that there was a failure, a return value of false indicates that
4377/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004378///
4379/// When @p SuppressUserConversions, user-defined conversions are
4380/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004381/// When @p AllowExplicit, we also permit explicit user-defined
4382/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004383/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004384/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4385/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004386bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004387Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004388 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004389 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004390 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004391 ImplicitConversionSequence *ICS,
4392 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004393 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4394
Ted Kremenek6217b802009-07-29 21:53:49 +00004395 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004396 QualType T2 = Init->getType();
4397
Douglas Gregor904eed32008-11-10 20:40:00 +00004398 // If the initializer is the address of an overloaded function, try
4399 // to resolve the overloaded function. If all goes well, T2 is the
4400 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004401 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004402 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004403 ICS != 0);
4404 if (Fn) {
4405 // Since we're performing this reference-initialization for
4406 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004407 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004408 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004409 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004410
Anders Carlsson96ad5332009-10-21 17:16:23 +00004411 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004412 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004413
4414 T2 = Fn->getType();
4415 }
4416 }
4417
Douglas Gregor15da57e2008-10-29 02:00:59 +00004418 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004419 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004420 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004421 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4422 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004423 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004424 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004425
4426 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004427 if (ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00004428 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCalladbb8f82010-01-13 09:16:55 +00004429 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004430
4431 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004432 // A reference to type "cv1 T1" is initialized by an expression
4433 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004434
4435 // -- If the initializer expression
4436
Sebastian Redla9845802009-03-29 15:27:50 +00004437 // Rvalue references cannot bind to lvalues (N2812).
4438 // There is absolutely no situation where they can. In particular, note that
4439 // this is ill-formed, even if B has a user-defined conversion to A&&:
4440 // B b;
4441 // A&& r = b;
4442 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4443 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004444 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004445 << Init->getSourceRange();
4446 return true;
4447 }
4448
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004449 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004450 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4451 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004452 //
4453 // Note that the bit-field check is skipped if we are just computing
4454 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004455 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004456 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004457 BindsDirectly = true;
4458
Douglas Gregor15da57e2008-10-29 02:00:59 +00004459 if (ICS) {
4460 // C++ [over.ics.ref]p1:
4461 // When a parameter of reference type binds directly (8.5.3)
4462 // to an argument expression, the implicit conversion sequence
4463 // is the identity conversion, unless the argument expression
4464 // has a type that is a derived class of the parameter type,
4465 // in which case the implicit conversion sequence is a
4466 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004467 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004468 ICS->Standard.First = ICK_Identity;
4469 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4470 ICS->Standard.Third = ICK_Identity;
4471 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004472 ICS->Standard.setToType(0, T2);
4473 ICS->Standard.setToType(1, T1);
4474 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004475 ICS->Standard.ReferenceBinding = true;
4476 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004477 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004478 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004479
4480 // Nothing more to do: the inaccessibility/ambiguity check for
4481 // derived-to-base conversions is suppressed when we're
4482 // computing the implicit conversion sequence (C++
4483 // [over.best.ics]p2).
4484 return false;
4485 } else {
4486 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004487 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4488 if (DerivedToBase)
4489 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004490 else if(CheckExceptionSpecCompatibility(Init, T1))
4491 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004492 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004493 }
4494 }
4495
4496 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004497 // implicitly converted to an lvalue of type "cv3 T3,"
4498 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004499 // 92) (this conversion is selected by enumerating the
4500 // applicable conversion functions (13.3.1.6) and choosing
4501 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004502 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004503 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004504 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004505 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004506
John McCall5769d612010-02-08 23:07:23 +00004507 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004508 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004509 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004510 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004511 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004512 NamedDecl *D = *I;
4513 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4514 if (isa<UsingShadowDecl>(D))
4515 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4516
Mike Stump1eb44332009-09-09 15:08:12 +00004517 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004518 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004519 CXXConversionDecl *Conv;
4520 if (ConvTemplate)
4521 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4522 else
John McCall701c89e2009-12-03 04:06:58 +00004523 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004524
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004525 // If the conversion function doesn't return a reference type,
4526 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004527 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004528 (AllowExplicit || !Conv->isExplicit())) {
4529 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004530 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004531 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004532 else
John McCall86820f52010-01-26 01:37:31 +00004533 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4534 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004535 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004536 }
4537
4538 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004539 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004540 case OR_Success:
Douglas Gregora1a9f032010-03-07 23:17:44 +00004541 // C++ [over.ics.ref]p1:
4542 //
4543 // [...] If the parameter binds directly to the result of
4544 // applying a conversion function to the argument
4545 // expression, the implicit conversion sequence is a
4546 // user-defined conversion sequence (13.3.3.1.2), with the
4547 // second standard conversion sequence either an identity
4548 // conversion or, if the conversion function returns an
4549 // entity of a type that is a derived class of the parameter
4550 // type, a derived-to-base Conversion.
4551 if (!Best->FinalConversion.DirectBinding)
4552 break;
4553
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004554 // This is a direct binding.
4555 BindsDirectly = true;
4556
4557 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004558 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004559 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4560 ICS->UserDefined.After = Best->FinalConversion;
4561 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004562 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004563 assert(ICS->UserDefined.After.ReferenceBinding &&
4564 ICS->UserDefined.After.DirectBinding &&
4565 "Expected a direct reference binding!");
4566 return false;
4567 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004568 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004569 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004570 CastExpr::CK_UserDefinedConversion,
4571 cast<CXXMethodDecl>(Best->Function),
4572 Owned(Init));
4573 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004574
4575 if (CheckExceptionSpecCompatibility(Init, T1))
4576 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004577 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4578 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004579 }
4580 break;
4581
4582 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004583 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004584 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004585 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4586 Cand != CandidateSet.end(); ++Cand)
4587 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004588 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004589 break;
4590 }
4591 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4592 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004593 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004594 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004595
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004596 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004597 case OR_Deleted:
4598 // There was no suitable conversion, or we found a deleted
4599 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004600 break;
4601 }
4602 }
Mike Stump1eb44332009-09-09 15:08:12 +00004603
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004604 if (BindsDirectly) {
4605 // C++ [dcl.init.ref]p4:
4606 // [...] In all cases where the reference-related or
4607 // reference-compatible relationship of two types is used to
4608 // establish the validity of a reference binding, and T1 is a
4609 // base class of T2, a program that necessitates such a binding
4610 // is ill-formed if T1 is an inaccessible (clause 11) or
4611 // ambiguous (10.2) base class of T2.
4612 //
4613 // Note that we only check this condition when we're allowed to
4614 // complain about errors, because we should not be checking for
4615 // ambiguity (or inaccessibility) unless the reference binding
4616 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004617 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004618 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004619 Init->getSourceRange(),
4620 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004621 else
4622 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004623 }
4624
4625 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004626 // type (i.e., cv1 shall be const), or the reference shall be an
4627 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004628 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004629 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004630 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004631 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004632 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004633 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004634 return true;
4635 }
4636
4637 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004638 // class type, and "cv1 T1" is reference-compatible with
4639 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004640 // following ways (the choice is implementation-defined):
4641 //
4642 // -- The reference is bound to the object represented by
4643 // the rvalue (see 3.10) or to a sub-object within that
4644 // object.
4645 //
Eli Friedman33a31382009-08-05 19:21:58 +00004646 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004647 // a constructor is called to copy the entire rvalue
4648 // object into the temporary. The reference is bound to
4649 // the temporary or to a sub-object within the
4650 // temporary.
4651 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004652 // The constructor that would be used to make the copy
4653 // shall be callable whether or not the copy is actually
4654 // done.
4655 //
Sebastian Redla9845802009-03-29 15:27:50 +00004656 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004657 // freedom, so we will always take the first option and never build
4658 // a temporary in this case. FIXME: We will, however, have to check
4659 // for the presence of a copy constructor in C++98/03 mode.
4660 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004661 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4662 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004663 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004664 ICS->Standard.First = ICK_Identity;
4665 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4666 ICS->Standard.Third = ICK_Identity;
4667 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004668 ICS->Standard.setToType(0, T2);
4669 ICS->Standard.setToType(1, T1);
4670 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004671 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004672 ICS->Standard.DirectBinding = false;
4673 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004674 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004675 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004676 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4677 if (DerivedToBase)
4678 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004679 else if(CheckExceptionSpecCompatibility(Init, T1))
4680 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004681 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004682 }
4683 return false;
4684 }
4685
Eli Friedman33a31382009-08-05 19:21:58 +00004686 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004687 // initialized from the initializer expression using the
4688 // rules for a non-reference copy initialization (8.5). The
4689 // reference is then bound to the temporary. If T1 is
4690 // reference-related to T2, cv1 must be the same
4691 // cv-qualification as, or greater cv-qualification than,
4692 // cv2; otherwise, the program is ill-formed.
4693 if (RefRelationship == Ref_Related) {
4694 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4695 // we would be reference-compatible or reference-compatible with
4696 // added qualification. But that wasn't the case, so the reference
4697 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004698 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004699 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004700 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004701 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004702 return true;
4703 }
4704
Douglas Gregor734d9862009-01-30 23:27:23 +00004705 // If at least one of the types is a class type, the types are not
4706 // related, and we aren't allowed any user conversions, the
4707 // reference binding fails. This case is important for breaking
4708 // recursion, since TryImplicitConversion below will attempt to
4709 // create a temporary through the use of a copy constructor.
4710 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4711 (T1->isRecordType() || T2->isRecordType())) {
4712 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004713 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004714 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004715 return true;
4716 }
4717
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004718 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004719 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004720 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004721 //
Sebastian Redla9845802009-03-29 15:27:50 +00004722 // When a parameter of reference type is not bound directly to
4723 // an argument expression, the conversion sequence is the one
4724 // required to convert the argument expression to the
4725 // underlying type of the reference according to
4726 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4727 // to copy-initializing a temporary of the underlying type with
4728 // the argument expression. Any difference in top-level
4729 // cv-qualification is subsumed by the initialization itself
4730 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004731 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4732 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004733 /*ForceRValue=*/false,
4734 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Sebastian Redla9845802009-03-29 15:27:50 +00004736 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004737 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004738 ICS->Standard.ReferenceBinding = true;
4739 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004740 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004741 ICS->UserDefined.After.ReferenceBinding = true;
4742 ICS->UserDefined.After.RRefBinding = isRValRef;
4743 }
John McCall1d318332010-01-12 00:44:57 +00004744 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004745 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004746 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004747 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004748 false, false,
4749 Conversions);
4750 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004751 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004752 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004753 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004754 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004755 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004756 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004757 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004758 }
4759 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004760 else {
4761 if (isRValRef)
4762 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4763 << Init->getSourceRange();
4764 else
4765 Diag(DeclLoc, diag::err_invalid_initialization)
4766 << DeclType << Init->getType() << Init->getSourceRange();
4767 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004768 }
4769 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004770 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004771}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004772
Anders Carlsson20d45d22009-12-12 00:32:00 +00004773static inline bool
4774CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4775 const FunctionDecl *FnDecl) {
4776 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4777 if (isa<NamespaceDecl>(DC)) {
4778 return SemaRef.Diag(FnDecl->getLocation(),
4779 diag::err_operator_new_delete_declared_in_namespace)
4780 << FnDecl->getDeclName();
4781 }
4782
4783 if (isa<TranslationUnitDecl>(DC) &&
4784 FnDecl->getStorageClass() == FunctionDecl::Static) {
4785 return SemaRef.Diag(FnDecl->getLocation(),
4786 diag::err_operator_new_delete_declared_static)
4787 << FnDecl->getDeclName();
4788 }
4789
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004790 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004791}
4792
Anders Carlsson156c78e2009-12-13 17:53:43 +00004793static inline bool
4794CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4795 CanQualType ExpectedResultType,
4796 CanQualType ExpectedFirstParamType,
4797 unsigned DependentParamTypeDiag,
4798 unsigned InvalidParamTypeDiag) {
4799 QualType ResultType =
4800 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4801
4802 // Check that the result type is not dependent.
4803 if (ResultType->isDependentType())
4804 return SemaRef.Diag(FnDecl->getLocation(),
4805 diag::err_operator_new_delete_dependent_result_type)
4806 << FnDecl->getDeclName() << ExpectedResultType;
4807
4808 // Check that the result type is what we expect.
4809 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4810 return SemaRef.Diag(FnDecl->getLocation(),
4811 diag::err_operator_new_delete_invalid_result_type)
4812 << FnDecl->getDeclName() << ExpectedResultType;
4813
4814 // A function template must have at least 2 parameters.
4815 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4816 return SemaRef.Diag(FnDecl->getLocation(),
4817 diag::err_operator_new_delete_template_too_few_parameters)
4818 << FnDecl->getDeclName();
4819
4820 // The function decl must have at least 1 parameter.
4821 if (FnDecl->getNumParams() == 0)
4822 return SemaRef.Diag(FnDecl->getLocation(),
4823 diag::err_operator_new_delete_too_few_parameters)
4824 << FnDecl->getDeclName();
4825
4826 // Check the the first parameter type is not dependent.
4827 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4828 if (FirstParamType->isDependentType())
4829 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4830 << FnDecl->getDeclName() << ExpectedFirstParamType;
4831
4832 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004833 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004834 ExpectedFirstParamType)
4835 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4836 << FnDecl->getDeclName() << ExpectedFirstParamType;
4837
4838 return false;
4839}
4840
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004841static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004842CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004843 // C++ [basic.stc.dynamic.allocation]p1:
4844 // A program is ill-formed if an allocation function is declared in a
4845 // namespace scope other than global scope or declared static in global
4846 // scope.
4847 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4848 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004849
4850 CanQualType SizeTy =
4851 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4852
4853 // C++ [basic.stc.dynamic.allocation]p1:
4854 // The return type shall be void*. The first parameter shall have type
4855 // std::size_t.
4856 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4857 SizeTy,
4858 diag::err_operator_new_dependent_param_type,
4859 diag::err_operator_new_param_type))
4860 return true;
4861
4862 // C++ [basic.stc.dynamic.allocation]p1:
4863 // The first parameter shall not have an associated default argument.
4864 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004865 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004866 diag::err_operator_new_default_arg)
4867 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4868
4869 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004870}
4871
4872static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004873CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4874 // C++ [basic.stc.dynamic.deallocation]p1:
4875 // A program is ill-formed if deallocation functions are declared in a
4876 // namespace scope other than global scope or declared static in global
4877 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004878 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4879 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004880
4881 // C++ [basic.stc.dynamic.deallocation]p2:
4882 // Each deallocation function shall return void and its first parameter
4883 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004884 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4885 SemaRef.Context.VoidPtrTy,
4886 diag::err_operator_delete_dependent_param_type,
4887 diag::err_operator_delete_param_type))
4888 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004889
Anders Carlsson46991d62009-12-12 00:16:02 +00004890 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4891 if (FirstParamType->isDependentType())
4892 return SemaRef.Diag(FnDecl->getLocation(),
4893 diag::err_operator_delete_dependent_param_type)
4894 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4895
4896 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4897 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004898 return SemaRef.Diag(FnDecl->getLocation(),
4899 diag::err_operator_delete_param_type)
4900 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004901
4902 return false;
4903}
4904
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004905/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4906/// of this overloaded operator is well-formed. If so, returns false;
4907/// otherwise, emits appropriate diagnostics and returns true.
4908bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004909 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004910 "Expected an overloaded operator declaration");
4911
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004912 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4913
Mike Stump1eb44332009-09-09 15:08:12 +00004914 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004915 // The allocation and deallocation functions, operator new,
4916 // operator new[], operator delete and operator delete[], are
4917 // described completely in 3.7.3. The attributes and restrictions
4918 // found in the rest of this subclause do not apply to them unless
4919 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004920 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004921 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004922
Anders Carlssona3ccda52009-12-12 00:26:23 +00004923 if (Op == OO_New || Op == OO_Array_New)
4924 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004925
4926 // C++ [over.oper]p6:
4927 // An operator function shall either be a non-static member
4928 // function or be a non-member function and have at least one
4929 // parameter whose type is a class, a reference to a class, an
4930 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004931 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4932 if (MethodDecl->isStatic())
4933 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004934 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004935 } else {
4936 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004937 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4938 ParamEnd = FnDecl->param_end();
4939 Param != ParamEnd; ++Param) {
4940 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004941 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4942 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004943 ClassOrEnumParam = true;
4944 break;
4945 }
4946 }
4947
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004948 if (!ClassOrEnumParam)
4949 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004950 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004951 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004952 }
4953
4954 // C++ [over.oper]p8:
4955 // An operator function cannot have default arguments (8.3.6),
4956 // except where explicitly stated below.
4957 //
Mike Stump1eb44332009-09-09 15:08:12 +00004958 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004959 // (C++ [over.call]p1).
4960 if (Op != OO_Call) {
4961 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4962 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004963 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004964 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004965 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004966 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004967 }
4968 }
4969
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004970 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4971 { false, false, false }
4972#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4973 , { Unary, Binary, MemberOnly }
4974#include "clang/Basic/OperatorKinds.def"
4975 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004976
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004977 bool CanBeUnaryOperator = OperatorUses[Op][0];
4978 bool CanBeBinaryOperator = OperatorUses[Op][1];
4979 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004980
4981 // C++ [over.oper]p8:
4982 // [...] Operator functions cannot have more or fewer parameters
4983 // than the number required for the corresponding operator, as
4984 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004985 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004986 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004987 if (Op != OO_Call &&
4988 ((NumParams == 1 && !CanBeUnaryOperator) ||
4989 (NumParams == 2 && !CanBeBinaryOperator) ||
4990 (NumParams < 1) || (NumParams > 2))) {
4991 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004992 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004993 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004994 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004995 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004996 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004997 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004998 assert(CanBeBinaryOperator &&
4999 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005000 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005001 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005002
Chris Lattner416e46f2008-11-21 07:57:12 +00005003 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005004 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005005 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005006
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005007 // Overloaded operators other than operator() cannot be variadic.
5008 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005009 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005010 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005011 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005012 }
5013
5014 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005015 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5016 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005017 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005018 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005019 }
5020
5021 // C++ [over.inc]p1:
5022 // The user-defined function called operator++ implements the
5023 // prefix and postfix ++ operator. If this function is a member
5024 // function with no parameters, or a non-member function with one
5025 // parameter of class or enumeration type, it defines the prefix
5026 // increment operator ++ for objects of that type. If the function
5027 // is a member function with one parameter (which shall be of type
5028 // int) or a non-member function with two parameters (the second
5029 // of which shall be of type int), it defines the postfix
5030 // increment operator ++ for objects of that type.
5031 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5032 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5033 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005034 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005035 ParamIsInt = BT->getKind() == BuiltinType::Int;
5036
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005037 if (!ParamIsInt)
5038 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005039 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005040 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005041 }
5042
Sebastian Redl64b45f72009-01-05 20:52:13 +00005043 // Notify the class if it got an assignment operator.
5044 if (Op == OO_Equal) {
5045 // Would have returned earlier otherwise.
5046 assert(isa<CXXMethodDecl>(FnDecl) &&
5047 "Overloaded = not member, but not filtered.");
5048 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5049 Method->getParent()->addedAssignmentOperator(Context, Method);
5050 }
5051
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005052 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005053}
Chris Lattner5a003a42008-12-17 07:09:26 +00005054
Sean Hunta6c058d2010-01-13 09:01:02 +00005055/// CheckLiteralOperatorDeclaration - Check whether the declaration
5056/// of this literal operator function is well-formed. If so, returns
5057/// false; otherwise, emits appropriate diagnostics and returns true.
5058bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5059 DeclContext *DC = FnDecl->getDeclContext();
5060 Decl::Kind Kind = DC->getDeclKind();
5061 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5062 Kind != Decl::LinkageSpec) {
5063 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5064 << FnDecl->getDeclName();
5065 return true;
5066 }
5067
5068 bool Valid = false;
5069
5070 // FIXME: Check for the one valid template signature
5071 // template <char...> type operator "" name();
5072
5073 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5074 // Check the first parameter
5075 QualType T = (*Param)->getType();
5076
5077 // unsigned long long int and long double are allowed, but only
5078 // alone.
5079 // We also allow any character type; their omission seems to be a bug
5080 // in n3000
5081 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5082 Context.hasSameType(T, Context.LongDoubleTy) ||
5083 Context.hasSameType(T, Context.CharTy) ||
5084 Context.hasSameType(T, Context.WCharTy) ||
5085 Context.hasSameType(T, Context.Char16Ty) ||
5086 Context.hasSameType(T, Context.Char32Ty)) {
5087 if (++Param == FnDecl->param_end())
5088 Valid = true;
5089 goto FinishedParams;
5090 }
5091
5092 // Otherwise it must be a pointer to const; let's strip those.
5093 const PointerType *PT = T->getAs<PointerType>();
5094 if (!PT)
5095 goto FinishedParams;
5096 T = PT->getPointeeType();
5097 if (!T.isConstQualified())
5098 goto FinishedParams;
5099 T = T.getUnqualifiedType();
5100
5101 // Move on to the second parameter;
5102 ++Param;
5103
5104 // If there is no second parameter, the first must be a const char *
5105 if (Param == FnDecl->param_end()) {
5106 if (Context.hasSameType(T, Context.CharTy))
5107 Valid = true;
5108 goto FinishedParams;
5109 }
5110
5111 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5112 // are allowed as the first parameter to a two-parameter function
5113 if (!(Context.hasSameType(T, Context.CharTy) ||
5114 Context.hasSameType(T, Context.WCharTy) ||
5115 Context.hasSameType(T, Context.Char16Ty) ||
5116 Context.hasSameType(T, Context.Char32Ty)))
5117 goto FinishedParams;
5118
5119 // The second and final parameter must be an std::size_t
5120 T = (*Param)->getType().getUnqualifiedType();
5121 if (Context.hasSameType(T, Context.getSizeType()) &&
5122 ++Param == FnDecl->param_end())
5123 Valid = true;
5124 }
5125
5126 // FIXME: This diagnostic is absolutely terrible.
5127FinishedParams:
5128 if (!Valid) {
5129 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5130 << FnDecl->getDeclName();
5131 return true;
5132 }
5133
5134 return false;
5135}
5136
Douglas Gregor074149e2009-01-05 19:45:36 +00005137/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5138/// linkage specification, including the language and (if present)
5139/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5140/// the location of the language string literal, which is provided
5141/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5142/// the '{' brace. Otherwise, this linkage specification does not
5143/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005144Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5145 SourceLocation ExternLoc,
5146 SourceLocation LangLoc,
5147 const char *Lang,
5148 unsigned StrSize,
5149 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005150 LinkageSpecDecl::LanguageIDs Language;
5151 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5152 Language = LinkageSpecDecl::lang_c;
5153 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5154 Language = LinkageSpecDecl::lang_cxx;
5155 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005156 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005157 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005158 }
Mike Stump1eb44332009-09-09 15:08:12 +00005159
Chris Lattnercc98eac2008-12-17 07:13:27 +00005160 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005161
Douglas Gregor074149e2009-01-05 19:45:36 +00005162 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005163 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005164 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005165 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005166 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005167 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005168}
5169
Douglas Gregor074149e2009-01-05 19:45:36 +00005170/// ActOnFinishLinkageSpecification - Completely the definition of
5171/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5172/// valid, it's the position of the closing '}' brace in a linkage
5173/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005174Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5175 DeclPtrTy LinkageSpec,
5176 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005177 if (LinkageSpec)
5178 PopDeclContext();
5179 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005180}
5181
Douglas Gregord308e622009-05-18 20:51:54 +00005182/// \brief Perform semantic analysis for the variable declaration that
5183/// occurs within a C++ catch clause, returning the newly-created
5184/// variable.
5185VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005186 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005187 IdentifierInfo *Name,
5188 SourceLocation Loc,
5189 SourceRange Range) {
5190 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005191
5192 // Arrays and functions decay.
5193 if (ExDeclType->isArrayType())
5194 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5195 else if (ExDeclType->isFunctionType())
5196 ExDeclType = Context.getPointerType(ExDeclType);
5197
5198 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5199 // The exception-declaration shall not denote a pointer or reference to an
5200 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005201 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005202 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005203 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005204 Invalid = true;
5205 }
Douglas Gregord308e622009-05-18 20:51:54 +00005206
Douglas Gregora2762912010-03-08 01:47:36 +00005207 // GCC allows catching pointers and references to incomplete types
5208 // as an extension; so do we, but we warn by default.
5209
Sebastian Redl4b07b292008-12-22 19:15:10 +00005210 QualType BaseType = ExDeclType;
5211 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005212 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00005213 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00005214 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005215 BaseType = Ptr->getPointeeType();
5216 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00005217 DK = diag::ext_catch_incomplete_ptr;
5218 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005219 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005220 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005221 BaseType = Ref->getPointeeType();
5222 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00005223 DK = diag::ext_catch_incomplete_ref;
5224 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005225 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005226 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00005227 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5228 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00005229 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005230
Mike Stump1eb44332009-09-09 15:08:12 +00005231 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005232 RequireNonAbstractType(Loc, ExDeclType,
5233 diag::err_abstract_type_in_decl,
5234 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005235 Invalid = true;
5236
Mike Stump1eb44332009-09-09 15:08:12 +00005237 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005238 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005239
Douglas Gregor6d182892010-03-05 23:38:39 +00005240 if (!Invalid) {
5241 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5242 // C++ [except.handle]p16:
5243 // The object declared in an exception-declaration or, if the
5244 // exception-declaration does not specify a name, a temporary (12.2) is
5245 // copy-initialized (8.5) from the exception object. [...]
5246 // The object is destroyed when the handler exits, after the destruction
5247 // of any automatic objects initialized within the handler.
5248 //
5249 // We just pretend to initialize the object with itself, then make sure
5250 // it can be destroyed later.
5251 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5252 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5253 Loc, ExDeclType, 0);
5254 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5255 SourceLocation());
5256 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5257 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5258 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5259 if (Result.isInvalid())
5260 Invalid = true;
5261 else
5262 FinalizeVarWithDestructor(ExDecl, RecordTy);
5263 }
5264 }
5265
Douglas Gregord308e622009-05-18 20:51:54 +00005266 if (Invalid)
5267 ExDecl->setInvalidDecl();
5268
5269 return ExDecl;
5270}
5271
5272/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5273/// handler.
5274Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005275 TypeSourceInfo *TInfo = 0;
5276 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005277
5278 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005279 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005280 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005281 // The scope should be freshly made just for us. There is just no way
5282 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005283 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005284 if (PrevDecl->isTemplateParameter()) {
5285 // Maybe we will complain about the shadowed template parameter.
5286 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005287 }
5288 }
5289
Chris Lattnereaaebc72009-04-25 08:06:05 +00005290 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005291 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5292 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005293 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005294 }
5295
John McCalla93c9342009-12-07 02:54:59 +00005296 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005297 D.getIdentifier(),
5298 D.getIdentifierLoc(),
5299 D.getDeclSpec().getSourceRange());
5300
Chris Lattnereaaebc72009-04-25 08:06:05 +00005301 if (Invalid)
5302 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Sebastian Redl4b07b292008-12-22 19:15:10 +00005304 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005305 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005306 PushOnScopeChains(ExDecl, S);
5307 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005308 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005309
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005310 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005311 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005312}
Anders Carlssonfb311762009-03-14 00:25:26 +00005313
Mike Stump1eb44332009-09-09 15:08:12 +00005314Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005315 ExprArg assertexpr,
5316 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005317 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005318 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005319 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5320
Anders Carlssonc3082412009-03-14 00:33:21 +00005321 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5322 llvm::APSInt Value(32);
5323 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5324 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5325 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005326 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005327 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005328
Anders Carlssonc3082412009-03-14 00:33:21 +00005329 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005330 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005331 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005332 }
5333 }
Mike Stump1eb44332009-09-09 15:08:12 +00005334
Anders Carlsson77d81422009-03-15 17:35:16 +00005335 assertexpr.release();
5336 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005337 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005338 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005340 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005341 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005342}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005343
John McCalldd4a3b02009-09-16 22:47:08 +00005344/// Handle a friend type declaration. This works in tandem with
5345/// ActOnTag.
5346///
5347/// Notes on friend class templates:
5348///
5349/// We generally treat friend class declarations as if they were
5350/// declaring a class. So, for example, the elaborated type specifier
5351/// in a friend declaration is required to obey the restrictions of a
5352/// class-head (i.e. no typedefs in the scope chain), template
5353/// parameters are required to match up with simple template-ids, &c.
5354/// However, unlike when declaring a template specialization, it's
5355/// okay to refer to a template specialization without an empty
5356/// template parameter declaration, e.g.
5357/// friend class A<T>::B<unsigned>;
5358/// We permit this as a special case; if there are any template
5359/// parameters present at all, require proper matching, i.e.
5360/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005361Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005362 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005363 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005364
5365 assert(DS.isFriendSpecified());
5366 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5367
John McCalldd4a3b02009-09-16 22:47:08 +00005368 // Try to convert the decl specifier to a type. This works for
5369 // friend templates because ActOnTag never produces a ClassTemplateDecl
5370 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005371 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005372 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5373 if (TheDeclarator.isInvalidType())
5374 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005375
John McCalldd4a3b02009-09-16 22:47:08 +00005376 // This is definitely an error in C++98. It's probably meant to
5377 // be forbidden in C++0x, too, but the specification is just
5378 // poorly written.
5379 //
5380 // The problem is with declarations like the following:
5381 // template <T> friend A<T>::foo;
5382 // where deciding whether a class C is a friend or not now hinges
5383 // on whether there exists an instantiation of A that causes
5384 // 'foo' to equal C. There are restrictions on class-heads
5385 // (which we declare (by fiat) elaborated friend declarations to
5386 // be) that makes this tractable.
5387 //
5388 // FIXME: handle "template <> friend class A<T>;", which
5389 // is possibly well-formed? Who even knows?
5390 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5391 Diag(Loc, diag::err_tagless_friend_type_template)
5392 << DS.getSourceRange();
5393 return DeclPtrTy();
5394 }
5395
John McCall02cace72009-08-28 07:59:38 +00005396 // C++ [class.friend]p2:
5397 // An elaborated-type-specifier shall be used in a friend declaration
5398 // for a class.*
5399 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005400 // This is one of the rare places in Clang where it's legitimate to
5401 // ask about the "spelling" of the type.
5402 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5403 // If we evaluated the type to a record type, suggest putting
5404 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005405 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005406 RecordDecl *RD = RT->getDecl();
5407
5408 std::string InsertionText = std::string(" ") + RD->getKindName();
5409
John McCalle3af0232009-10-07 23:34:25 +00005410 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5411 << (unsigned) RD->getTagKind()
5412 << T
5413 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005414 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5415 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005416 return DeclPtrTy();
5417 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005418 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5419 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005420 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005421 }
5422 }
5423
John McCalle3af0232009-10-07 23:34:25 +00005424 // Enum types cannot be friends.
5425 if (T->getAs<EnumType>()) {
5426 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5427 << SourceRange(DS.getFriendSpecLoc());
5428 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005429 }
John McCall02cace72009-08-28 07:59:38 +00005430
John McCall02cace72009-08-28 07:59:38 +00005431 // C++98 [class.friend]p1: A friend of a class is a function
5432 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005433 // This is fixed in DR77, which just barely didn't make the C++03
5434 // deadline. It's also a very silly restriction that seriously
5435 // affects inner classes and which nobody else seems to implement;
5436 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005437
John McCalldd4a3b02009-09-16 22:47:08 +00005438 Decl *D;
5439 if (TempParams.size())
5440 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5441 TempParams.size(),
5442 (TemplateParameterList**) TempParams.release(),
5443 T.getTypePtr(),
5444 DS.getFriendSpecLoc());
5445 else
5446 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5447 DS.getFriendSpecLoc());
5448 D->setAccess(AS_public);
5449 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005450
John McCalldd4a3b02009-09-16 22:47:08 +00005451 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005452}
5453
John McCallbbbcdd92009-09-11 21:02:39 +00005454Sema::DeclPtrTy
5455Sema::ActOnFriendFunctionDecl(Scope *S,
5456 Declarator &D,
5457 bool IsDefinition,
5458 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005459 const DeclSpec &DS = D.getDeclSpec();
5460
5461 assert(DS.isFriendSpecified());
5462 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5463
5464 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005465 TypeSourceInfo *TInfo = 0;
5466 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005467
5468 // C++ [class.friend]p1
5469 // A friend of a class is a function or class....
5470 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005471 // It *doesn't* see through dependent types, which is correct
5472 // according to [temp.arg.type]p3:
5473 // If a declaration acquires a function type through a
5474 // type dependent on a template-parameter and this causes
5475 // a declaration that does not use the syntactic form of a
5476 // function declarator to have a function type, the program
5477 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005478 if (!T->isFunctionType()) {
5479 Diag(Loc, diag::err_unexpected_friend);
5480
5481 // It might be worthwhile to try to recover by creating an
5482 // appropriate declaration.
5483 return DeclPtrTy();
5484 }
5485
5486 // C++ [namespace.memdef]p3
5487 // - If a friend declaration in a non-local class first declares a
5488 // class or function, the friend class or function is a member
5489 // of the innermost enclosing namespace.
5490 // - The name of the friend is not found by simple name lookup
5491 // until a matching declaration is provided in that namespace
5492 // scope (either before or after the class declaration granting
5493 // friendship).
5494 // - If a friend function is called, its name may be found by the
5495 // name lookup that considers functions from namespaces and
5496 // classes associated with the types of the function arguments.
5497 // - When looking for a prior declaration of a class or a function
5498 // declared as a friend, scopes outside the innermost enclosing
5499 // namespace scope are not considered.
5500
John McCall02cace72009-08-28 07:59:38 +00005501 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5502 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005503 assert(Name);
5504
John McCall67d1a672009-08-06 02:15:43 +00005505 // The context we found the declaration in, or in which we should
5506 // create the declaration.
5507 DeclContext *DC;
5508
5509 // FIXME: handle local classes
5510
5511 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005512 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5513 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005514 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005515 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005516 DC = computeDeclContext(ScopeQual);
5517
5518 // FIXME: handle dependent contexts
5519 if (!DC) return DeclPtrTy();
5520
John McCall68263142009-11-18 22:49:29 +00005521 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005522
5523 // If searching in that context implicitly found a declaration in
5524 // a different context, treat it like it wasn't found at all.
5525 // TODO: better diagnostics for this case. Suggesting the right
5526 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005527 // FIXME: getRepresentativeDecl() is not right here at all
5528 if (Previous.empty() ||
5529 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005530 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005531 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5532 return DeclPtrTy();
5533 }
5534
5535 // C++ [class.friend]p1: A friend of a class is a function or
5536 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005537 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005538 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5539
John McCall67d1a672009-08-06 02:15:43 +00005540 // Otherwise walk out to the nearest namespace scope looking for matches.
5541 } else {
5542 // TODO: handle local class contexts.
5543
5544 DC = CurContext;
5545 while (true) {
5546 // Skip class contexts. If someone can cite chapter and verse
5547 // for this behavior, that would be nice --- it's what GCC and
5548 // EDG do, and it seems like a reasonable intent, but the spec
5549 // really only says that checks for unqualified existing
5550 // declarations should stop at the nearest enclosing namespace,
5551 // not that they should only consider the nearest enclosing
5552 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005553 while (DC->isRecord())
5554 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005555
John McCall68263142009-11-18 22:49:29 +00005556 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005557
5558 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005559 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005560 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005561
John McCall67d1a672009-08-06 02:15:43 +00005562 if (DC->isFileContext()) break;
5563 DC = DC->getParent();
5564 }
5565
5566 // C++ [class.friend]p1: A friend of a class is a function or
5567 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005568 // C++0x changes this for both friend types and functions.
5569 // Most C++ 98 compilers do seem to give an error here, so
5570 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005571 if (!Previous.empty() && DC->Equals(CurContext)
5572 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005573 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5574 }
5575
Douglas Gregor182ddf02009-09-28 00:08:27 +00005576 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005577 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005578 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5579 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5580 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005581 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005582 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5583 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005584 return DeclPtrTy();
5585 }
John McCall67d1a672009-08-06 02:15:43 +00005586 }
5587
Douglas Gregor182ddf02009-09-28 00:08:27 +00005588 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005589 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005590 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005591 IsDefinition,
5592 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005593 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005594
Douglas Gregor182ddf02009-09-28 00:08:27 +00005595 assert(ND->getDeclContext() == DC);
5596 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005597
John McCallab88d972009-08-31 22:39:49 +00005598 // Add the function declaration to the appropriate lookup tables,
5599 // adjusting the redeclarations list as necessary. We don't
5600 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005601 //
John McCallab88d972009-08-31 22:39:49 +00005602 // Also update the scope-based lookup if the target context's
5603 // lookup context is in lexical scope.
5604 if (!CurContext->isDependentContext()) {
5605 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005606 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005607 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005608 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005609 }
John McCall02cace72009-08-28 07:59:38 +00005610
5611 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005612 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005613 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005614 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005615 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005616
Douglas Gregor7557a132009-12-24 20:56:24 +00005617 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5618 FrD->setSpecialization(true);
5619
Douglas Gregor182ddf02009-09-28 00:08:27 +00005620 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005621}
5622
Chris Lattnerb28317a2009-03-28 19:18:32 +00005623void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005624 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005625
Chris Lattnerb28317a2009-03-28 19:18:32 +00005626 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005627 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5628 if (!Fn) {
5629 Diag(DelLoc, diag::err_deleted_non_function);
5630 return;
5631 }
5632 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5633 Diag(DelLoc, diag::err_deleted_decl_not_first);
5634 Diag(Prev->getLocation(), diag::note_previous_declaration);
5635 // If the declaration wasn't the first, we delete the function anyway for
5636 // recovery.
5637 }
5638 Fn->setDeleted();
5639}
Sebastian Redl13e88542009-04-27 21:33:24 +00005640
5641static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5642 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5643 ++CI) {
5644 Stmt *SubStmt = *CI;
5645 if (!SubStmt)
5646 continue;
5647 if (isa<ReturnStmt>(SubStmt))
5648 Self.Diag(SubStmt->getSourceRange().getBegin(),
5649 diag::err_return_in_constructor_handler);
5650 if (!isa<Expr>(SubStmt))
5651 SearchForReturnInStmt(Self, SubStmt);
5652 }
5653}
5654
5655void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5656 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5657 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5658 SearchForReturnInStmt(*this, Handler);
5659 }
5660}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005661
Mike Stump1eb44332009-09-09 15:08:12 +00005662bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005663 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005664 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5665 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005666
Chandler Carruth73857792010-02-15 11:53:20 +00005667 if (Context.hasSameType(NewTy, OldTy) ||
5668 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005669 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005670
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005671 // Check if the return types are covariant
5672 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005673
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005674 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005675 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5676 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005677 NewClassTy = NewPT->getPointeeType();
5678 OldClassTy = OldPT->getPointeeType();
5679 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005680 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5681 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5682 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5683 NewClassTy = NewRT->getPointeeType();
5684 OldClassTy = OldRT->getPointeeType();
5685 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005686 }
5687 }
Mike Stump1eb44332009-09-09 15:08:12 +00005688
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005689 // The return types aren't either both pointers or references to a class type.
5690 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005691 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005692 diag::err_different_return_type_for_overriding_virtual_function)
5693 << New->getDeclName() << NewTy << OldTy;
5694 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005695
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005696 return true;
5697 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005698
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005699 // C++ [class.virtual]p6:
5700 // If the return type of D::f differs from the return type of B::f, the
5701 // class type in the return type of D::f shall be complete at the point of
5702 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005703 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5704 if (!RT->isBeingDefined() &&
5705 RequireCompleteType(New->getLocation(), NewClassTy,
5706 PDiag(diag::err_covariant_return_incomplete)
5707 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005708 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005709 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005710
Douglas Gregora4923eb2009-11-16 21:35:15 +00005711 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005712 // Check if the new class derives from the old class.
5713 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5714 Diag(New->getLocation(),
5715 diag::err_covariant_return_not_derived)
5716 << New->getDeclName() << NewTy << OldTy;
5717 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 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005722 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005723 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5724 // FIXME: Should this point to the return type?
5725 New->getLocation(), SourceRange(), New->getDeclName())) {
5726 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5727 return true;
5728 }
5729 }
Mike Stump1eb44332009-09-09 15:08:12 +00005730
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005731 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005732 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005733 Diag(New->getLocation(),
5734 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005735 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005736 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5737 return true;
5738 };
Mike Stump1eb44332009-09-09 15:08:12 +00005739
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005740
5741 // The new class type must have the same or less qualifiers as the old type.
5742 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5743 Diag(New->getLocation(),
5744 diag::err_covariant_return_type_class_type_more_qualified)
5745 << New->getDeclName() << NewTy << OldTy;
5746 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5747 return true;
5748 };
Mike Stump1eb44332009-09-09 15:08:12 +00005749
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005750 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005751}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005752
Sean Huntbbd37c62009-11-21 08:43:09 +00005753bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5754 const CXXMethodDecl *Old)
5755{
5756 if (Old->hasAttr<FinalAttr>()) {
5757 Diag(New->getLocation(), diag::err_final_function_overridden)
5758 << New->getDeclName();
5759 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5760 return true;
5761 }
5762
5763 return false;
5764}
5765
Douglas Gregor4ba31362009-12-01 17:24:26 +00005766/// \brief Mark the given method pure.
5767///
5768/// \param Method the method to be marked pure.
5769///
5770/// \param InitRange the source range that covers the "0" initializer.
5771bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5772 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5773 Method->setPure();
5774
5775 // A class is abstract if at least one function is pure virtual.
5776 Method->getParent()->setAbstract(true);
5777 return false;
5778 }
5779
5780 if (!Method->isInvalidDecl())
5781 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5782 << Method->getDeclName() << InitRange;
5783 return true;
5784}
5785
John McCall731ad842009-12-19 09:28:58 +00005786/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5787/// an initializer for the out-of-line declaration 'Dcl'. The scope
5788/// is a fresh scope pushed for just this purpose.
5789///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005790/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5791/// static data member of class X, names should be looked up in the scope of
5792/// class X.
5793void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005794 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005795 Decl *D = Dcl.getAs<Decl>();
5796 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005797
John McCall731ad842009-12-19 09:28:58 +00005798 // We should only get called for declarations with scope specifiers, like:
5799 // int foo::bar;
5800 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005801 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005802}
5803
5804/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005805/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005806void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005807 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005808 Decl *D = Dcl.getAs<Decl>();
5809 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005810
John McCall731ad842009-12-19 09:28:58 +00005811 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005812 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005813}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005814
5815/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5816/// C++ if/switch/while/for statement.
5817/// e.g: "if (int x = f()) {...}"
5818Action::DeclResult
5819Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5820 // C++ 6.4p2:
5821 // The declarator shall not specify a function or an array.
5822 // The type-specifier-seq shall not contain typedef and shall not declare a
5823 // new class or enumeration.
5824 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5825 "Parser allowed 'typedef' as storage class of condition decl.");
5826
John McCalla93c9342009-12-07 02:54:59 +00005827 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005828 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005829 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005830
5831 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5832 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5833 // would be created and CXXConditionDeclExpr wants a VarDecl.
5834 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5835 << D.getSourceRange();
5836 return DeclResult();
5837 } else if (OwnedTag && OwnedTag->isDefinition()) {
5838 // The type-specifier-seq shall not declare a new class or enumeration.
5839 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5840 }
5841
5842 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5843 if (!Dcl)
5844 return DeclResult();
5845
5846 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5847 VD->setDeclaredInCondition(true);
5848 return Dcl;
5849}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005850
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005851static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005852 // Ignore dependent types.
5853 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005854 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005855
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005856 // Ignore declarations that are not definitions.
5857 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005858 return false;
5859
5860 CXXRecordDecl *RD = MD->getParent();
5861
5862 // Ignore classes without a vtable.
5863 if (!RD->isDynamicClass())
5864 return false;
5865
5866 switch (MD->getParent()->getTemplateSpecializationKind()) {
5867 case TSK_Undeclared:
5868 case TSK_ExplicitSpecialization:
5869 // Classes that aren't instantiations of templates don't need their
5870 // virtual methods marked until we see the definition of the key
5871 // function.
5872 break;
5873
5874 case TSK_ImplicitInstantiation:
5875 // This is a constructor of a class template; mark all of the virtual
5876 // members as referenced to ensure that they get instantiatied.
5877 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5878 return true;
5879 break;
5880
5881 case TSK_ExplicitInstantiationDeclaration:
5882 return true; //FIXME: This looks wrong.
5883
5884 case TSK_ExplicitInstantiationDefinition:
5885 // This is method of a explicit instantiation; mark all of the virtual
5886 // members as referenced to ensure that they get instantiatied.
5887 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005888 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005889
5890 // Consider only out-of-line definitions of member functions. When we see
5891 // an inline definition, it's too early to compute the key function.
5892 if (!MD->isOutOfLine())
5893 return false;
5894
5895 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5896
5897 // If there is no key function, we will need a copy of the vtable.
5898 if (!KeyFunction)
5899 return true;
5900
5901 // If this is the key function, we need to mark virtual members.
5902 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5903 return true;
5904
5905 return false;
5906}
5907
5908void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5909 CXXMethodDecl *MD) {
5910 CXXRecordDecl *RD = MD->getParent();
5911
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005912 // We will need to mark all of the virtual members as referenced to build the
5913 // vtable.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00005914 if (!needsVtable(MD, Context))
5915 return;
5916
5917 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5918 if (kind == TSK_ImplicitInstantiation)
5919 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5920 else
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005921 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005922}
5923
5924bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5925 if (ClassesWithUnmarkedVirtualMembers.empty())
5926 return false;
5927
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005928 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5929 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5930 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5931 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005932 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005933 }
5934
Anders Carlssond6a637f2009-12-07 08:24:59 +00005935 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005936}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005937
5938void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5939 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5940 e = RD->method_end(); i != e; ++i) {
5941 CXXMethodDecl *MD = *i;
5942
5943 // C++ [basic.def.odr]p2:
5944 // [...] A virtual member function is used if it is not pure. [...]
5945 if (MD->isVirtual() && !MD->isPure())
5946 MarkDeclarationReferenced(Loc, MD);
5947 }
5948}