blob: 7693e144ba2e759a66d197456587b1e7fcb96bd7 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlssonf98849e2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000030#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000031#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner58258242008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattnerb0d38442008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000049
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 public:
Mike Stump11289f42009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 };
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000066 }
67
Chris Lattnerb0d38442008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000093 }
Chris Lattner58258242008-04-10 02:22:51 +000094
Douglas Gregor8e12c382008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000097
Douglas Gregor97a9c812008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107}
108
Anders Carlssonc80a1272009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000119
Anders Carlssonc80a1272009-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 Gregor85dabae2009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman5f101b92009-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 Carlsson4562f1f2009-08-25 03:18:48 +0000133 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000135
Anders Carlsson6e997b22009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000137
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Anders Carlssonc80a1272009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000142
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000143 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000144}
145
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000149void
Mike Stump11289f42009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattner83f095c2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlssonf1c26952009-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 Stump11289f42009-09-09 15:08:12 +0000174
Anders Carlssonc80a1272009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000176}
177
Douglas Gregor58354032008-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 Stump11289f42009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner83f095c2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000191
Anders Carlsson84613c42009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000193}
194
Douglas Gregor4d87df52008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump11289f42009-09-09 15:08:12 +0000200
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000202
Anders Carlsson84613c42009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000204
Anders Carlsson84613c42009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000206}
207
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-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 Gregor58354032008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-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 Stump11289f42009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor75a45ba2009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
John McCallf3cd6652010-03-12 18:31:32 +0000301 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000302 if (OldParam->hasUninstantiatedDefaultArg())
303 NewParam->setUninstantiatedDefaultArg(
304 OldParam->getUninstantiatedDefaultArg());
305 else
306 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000307 } else if (NewParam->hasDefaultArg()) {
308 if (New->getDescribedFunctionTemplate()) {
309 // Paragraph 4, quoted above, only applies to non-template functions.
310 Diag(NewParam->getLocation(),
311 diag::err_param_default_argument_template_redecl)
312 << NewParam->getDefaultArgRange();
313 Diag(Old->getLocation(), diag::note_template_prev_declaration)
314 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000315 } else if (New->getTemplateSpecializationKind()
316 != TSK_ImplicitInstantiation &&
317 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318 // C++ [temp.expr.spec]p21:
319 // Default function arguments shall not be specified in a declaration
320 // or a definition for one of the following explicit specializations:
321 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000322 // - the explicit specialization of a member function template;
323 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000324 // template where the class template specialization to which the
325 // member function specialization belongs is implicitly
326 // instantiated.
327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329 << New->getDeclName()
330 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000331 } else if (New->getDeclContext()->isDependentContext()) {
332 // C++ [dcl.fct.default]p6 (DR217):
333 // Default arguments for a member function of a class template shall
334 // be specified on the initial declaration of the member function
335 // within the class template.
336 //
337 // Reading the tea leaves a bit in DR217 and its reference to DR205
338 // leads me to the conclusion that one cannot add default function
339 // arguments for an out-of-line definition of a member function of a
340 // dependent type.
341 int WhichKind = 2;
342 if (CXXRecordDecl *Record
343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344 if (Record->getDescribedClassTemplate())
345 WhichKind = 0;
346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347 WhichKind = 1;
348 else
349 WhichKind = 2;
350 }
351
352 Diag(NewParam->getLocation(),
353 diag::err_param_default_argument_member_template_redecl)
354 << WhichKind
355 << NewParam->getDefaultArgRange();
356 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000357 }
358 }
359
Douglas Gregorf40863c2010-02-12 07:32:17 +0000360 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000362
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000396 else
Mike Stump11289f42009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattner199abbc2008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000412 if (!Param->hasUnparsedDefaultArg())
413 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000414 Param->setDefaultArg(0);
415 }
416 }
417 }
418}
Douglas Gregor556877c2008-04-13 21:30:24 +0000419
Douglas Gregor61956c42008-10-31 09:07:45 +0000420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000426 assert(getLangOptions().CPlusPlus && "No class names in C!");
427
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000428 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000429 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000430 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
432 } else
433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
434
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000435 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000436 return &II == CurDecl->getIdentifier();
437 else
438 return false;
439}
440
Mike Stump11289f42009-09-09 15:08:12 +0000441/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000442///
443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
444/// and returns NULL otherwise.
445CXXBaseSpecifier *
446Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
447 SourceRange SpecifierRange,
448 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000449 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000450 SourceLocation BaseLoc) {
451 // C++ [class.union]p1:
452 // A union shall not have base classes.
453 if (Class->isUnion()) {
454 Diag(Class->getLocation(), diag::err_base_clause_on_union)
455 << SpecifierRange;
456 return 0;
457 }
458
459 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000461 Class->getTagKind() == RecordDecl::TK_class,
462 Access, BaseType);
463
464 // Base specifiers must be record types.
465 if (!BaseType->isRecordType()) {
466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
467 return 0;
468 }
469
470 // C++ [class.union]p1:
471 // A union shall not be used as a base class.
472 if (BaseType->isUnionType()) {
473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
474 return 0;
475 }
476
477 // C++ [class.derived]p2:
478 // The class-name in a base-specifier shall not be an incompletely
479 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000480 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000481 PDiag(diag::err_incomplete_base_class)
482 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000483 return 0;
484
Eli Friedmanc96d4962009-08-15 21:55:26 +0000485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000487 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000488 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000489 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000490 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
491 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000492
Alexis Hunt96d5c762009-11-21 08:43:09 +0000493 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
494 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
495 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000496 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
497 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000498 return 0;
499 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000500
Eli Friedman89c038e2009-12-05 23:03:49 +0000501 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000502
503 // Create the base specifier.
504 // FIXME: Allocate via ASTContext?
505 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
506 Class->getTagKind() == RecordDecl::TK_class,
507 Access, BaseType);
508}
509
510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
511 const CXXRecordDecl *BaseClass,
512 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000513 // A class with a non-empty base class is not empty.
514 // FIXME: Standard ref?
515 if (!BaseClass->isEmpty())
516 Class->setEmpty(false);
517
518 // C++ [class.virtual]p1:
519 // A class that [...] inherits a virtual function is called a polymorphic
520 // class.
521 if (BaseClass->isPolymorphic())
522 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000523
Douglas Gregor463421d2009-03-03 04:44:36 +0000524 // C++ [dcl.init.aggr]p1:
525 // An aggregate is [...] a class with [...] no base classes [...].
526 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000527
528 // C++ [class]p4:
529 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000530 Class->setPOD(false);
531
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000532 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000533 // C++ [class.ctor]p5:
534 // A constructor is trivial if its class has no virtual base classes.
535 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000536
537 // C++ [class.copy]p6:
538 // A copy constructor is trivial if its class has no virtual base classes.
539 Class->setHasTrivialCopyConstructor(false);
540
541 // C++ [class.copy]p11:
542 // A copy assignment operator is trivial if its class has no virtual
543 // base classes.
544 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000545
546 // C++0x [meta.unary.prop] is_empty:
547 // T is a class type, but not a union type, with ... no virtual base
548 // classes
549 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000550 } else {
551 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000552 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000553 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000554 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000555 Class->setHasTrivialConstructor(false);
556
557 // C++ [class.copy]p6:
558 // A copy constructor is trivial if all the direct base classes of its
559 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000560 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000561 Class->setHasTrivialCopyConstructor(false);
562
563 // C++ [class.copy]p11:
564 // A copy assignment operator is trivial if all the direct base classes
565 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000566 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000567 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000568 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000569
570 // C++ [class.ctor]p3:
571 // A destructor is trivial if all the direct base classes of its class
572 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000573 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000574 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000575}
576
Douglas Gregor556877c2008-04-13 21:30:24 +0000577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
578/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000579/// example:
580/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000581/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000582Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000584 bool Virtual, AccessSpecifier Access,
585 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000586 if (!classdecl)
587 return true;
588
Douglas Gregorc40290e2009-03-09 23:48:35 +0000589 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000590 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
591 if (!Class)
592 return true;
593
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000594 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000595 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
596 Virtual, Access,
597 BaseType, BaseLoc))
598 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000599
Douglas Gregor463421d2009-03-03 04:44:36 +0000600 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000601}
Douglas Gregor556877c2008-04-13 21:30:24 +0000602
Douglas Gregor463421d2009-03-03 04:44:36 +0000603/// \brief Performs the actual work of attaching the given base class
604/// specifiers to a C++ class.
605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
606 unsigned NumBases) {
607 if (NumBases == 0)
608 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000609
610 // Used to keep track of which base types we have already seen, so
611 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000612 // that the key is always the unqualified canonical type of the base
613 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000614 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
615
616 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000617 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000619 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000620 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000622 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000623
Douglas Gregor29a92472008-10-22 17:49:05 +0000624 if (KnownBaseTypes[NewBaseType]) {
625 // C++ [class.mi]p3:
626 // A class shall not be specified as a direct base class of a
627 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000628 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000629 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000630 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000632
633 // Delete the duplicate base class specifier; we're going to
634 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000635 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000636
637 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000638 } else {
639 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000640 KnownBaseTypes[NewBaseType] = Bases[idx];
641 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000642 }
643 }
644
645 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000646 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000647
648 // Delete the remaining (good) base class specifiers, since their
649 // data has been copied into the CXXRecordDecl.
650 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000651 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000652
653 return Invalid;
654}
655
656/// ActOnBaseSpecifiers - Attach the given base specifiers to the
657/// class, after checking whether there are any duplicate base
658/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000659void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000660 unsigned NumBases) {
661 if (!ClassDecl || !Bases || !NumBases)
662 return;
663
664 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000666 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000667}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000668
John McCalle78aac42010-03-10 03:28:59 +0000669static CXXRecordDecl *GetClassForType(QualType T) {
670 if (const RecordType *RT = T->getAs<RecordType>())
671 return cast<CXXRecordDecl>(RT->getDecl());
672 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
673 return ICT->getDecl();
674 else
675 return 0;
676}
677
Douglas Gregor36d1b142009-10-06 17:59:45 +0000678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
John McCalle78aac42010-03-10 03:28:59 +0000683
684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
John McCalle78aac42010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000690 return false;
691
John McCall67da35c2010-02-04 22:26:26 +0000692 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
693 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000694}
695
696/// \brief Determine whether the type \p Derived is a C++ class that is
697/// derived from the type \p Base.
698bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
699 if (!getLangOptions().CPlusPlus)
700 return false;
701
John McCalle78aac42010-03-10 03:28:59 +0000702 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
703 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000704 return false;
705
John McCalle78aac42010-03-10 03:28:59 +0000706 CXXRecordDecl *BaseRD = GetClassForType(Base);
707 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000708 return false;
709
Douglas Gregor36d1b142009-10-06 17:59:45 +0000710 return DerivedRD->isDerivedFrom(BaseRD, Paths);
711}
712
713/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
714/// conversion (where Derived and Base are class types) is
715/// well-formed, meaning that the conversion is unambiguous (and
716/// that all of the base classes are accessible). Returns true
717/// and emits a diagnostic if the code is ill-formed, returns false
718/// otherwise. Loc is the location where this routine should point to
719/// if there is an error, and Range is the source range to highlight
720/// if there is an error.
721bool
722Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall5b0829a2010-02-10 09:31:12 +0000723 AccessDiagnosticsKind ADK,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000724 unsigned AmbigiousBaseConvID,
725 SourceLocation Loc, SourceRange Range,
726 DeclarationName Name) {
727 // First, determine whether the path from Derived to Base is
728 // ambiguous. This is slightly more expensive than checking whether
729 // the Derived to Base conversion exists, because here we need to
730 // explore multiple paths to determine if there is an ambiguity.
731 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
732 /*DetectVirtual=*/false);
733 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
734 assert(DerivationOkay &&
735 "Can only be used with a derived-to-base conversion");
736 (void)DerivationOkay;
737
738 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall5b0829a2010-02-10 09:31:12 +0000739 if (ADK == ADK_quiet)
Sebastian Redl7c353682009-11-14 21:15:49 +0000740 return false;
John McCall5b0829a2010-02-10 09:31:12 +0000741
Douglas Gregor36d1b142009-10-06 17:59:45 +0000742 // Check that the base class can be accessed.
John McCall5b0829a2010-02-10 09:31:12 +0000743 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
744 Base, Derived, Paths.front(),
745 /*force*/ false,
746 /*unprivileged*/ false,
747 ADK)) {
748 case AR_accessible: return false;
749 case AR_inaccessible: return true;
750 case AR_dependent: return false;
751 case AR_delayed: return false;
752 }
Douglas Gregor36d1b142009-10-06 17:59:45 +0000753 }
754
755 // We know that the derived-to-base conversion is ambiguous, and
756 // we're going to produce a diagnostic. Perform the derived-to-base
757 // search just one more time to compute all of the possible paths so
758 // that we can print them out. This is more expensive than any of
759 // the previous derived-to-base checks we've done, but at this point
760 // performance isn't as much of an issue.
761 Paths.clear();
762 Paths.setRecordingPaths(true);
763 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
764 assert(StillOkay && "Can only be used with a derived-to-base conversion");
765 (void)StillOkay;
766
767 // Build up a textual representation of the ambiguous paths, e.g.,
768 // D -> B -> A, that will be used to illustrate the ambiguous
769 // conversions in the diagnostic. We only print one of the paths
770 // to each base class subobject.
771 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
772
773 Diag(Loc, AmbigiousBaseConvID)
774 << Derived << Base << PathDisplayStr << Range << Name;
775 return true;
776}
777
778bool
779Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000780 SourceLocation Loc, SourceRange Range,
781 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000782 return CheckDerivedToBaseConversion(Derived, Base,
John McCall5b0829a2010-02-10 09:31:12 +0000783 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000784 diag::err_ambiguous_derived_to_base_conv,
785 Loc, Range, DeclarationName());
786}
787
788
789/// @brief Builds a string representing ambiguous paths from a
790/// specific derived class to different subobjects of the same base
791/// class.
792///
793/// This function builds a string that can be used in error messages
794/// to show the different paths that one can take through the
795/// inheritance hierarchy to go from the derived class to different
796/// subobjects of a base class. The result looks something like this:
797/// @code
798/// struct D -> struct B -> struct A
799/// struct D -> struct C -> struct A
800/// @endcode
801std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
802 std::string PathDisplayStr;
803 std::set<unsigned> DisplayedPaths;
804 for (CXXBasePaths::paths_iterator Path = Paths.begin();
805 Path != Paths.end(); ++Path) {
806 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
807 // We haven't displayed a path to this particular base
808 // class subobject yet.
809 PathDisplayStr += "\n ";
810 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
811 for (CXXBasePath::const_iterator Element = Path->begin();
812 Element != Path->end(); ++Element)
813 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
814 }
815 }
816
817 return PathDisplayStr;
818}
819
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000820//===----------------------------------------------------------------------===//
821// C++ class member Handling
822//===----------------------------------------------------------------------===//
823
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000824/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
825/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
826/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000827/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000828Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000829Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000830 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000831 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
832 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000833 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000834 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000835 Expr *BitWidth = static_cast<Expr*>(BW);
836 Expr *Init = static_cast<Expr*>(InitExpr);
837 SourceLocation Loc = D.getIdentifierLoc();
838
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000839 bool isFunc = D.isFunctionDeclarator();
840
John McCall07e91c02009-08-06 02:15:43 +0000841 assert(!DS.isFriendSpecified());
842
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000843 // C++ 9.2p6: A member shall not be declared to have automatic storage
844 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000845 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
846 // data members and cannot be applied to names declared const or static,
847 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000848 switch (DS.getStorageClassSpec()) {
849 case DeclSpec::SCS_unspecified:
850 case DeclSpec::SCS_typedef:
851 case DeclSpec::SCS_static:
852 // FALL THROUGH.
853 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000854 case DeclSpec::SCS_mutable:
855 if (isFunc) {
856 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000857 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000858 else
Chris Lattner3b054132008-11-19 05:08:23 +0000859 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000860
Sebastian Redl8071edb2008-11-17 23:24:37 +0000861 // FIXME: It would be nicer if the keyword was ignored only for this
862 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000863 D.getMutableDeclSpec().ClearStorageClassSpecs();
864 } else {
865 QualType T = GetTypeForDeclarator(D, S);
866 diag::kind err = static_cast<diag::kind>(0);
867 if (T->isReferenceType())
868 err = diag::err_mutable_reference;
869 else if (T.isConstQualified())
870 err = diag::err_mutable_const;
871 if (err != 0) {
872 if (DS.getStorageClassSpecLoc().isValid())
873 Diag(DS.getStorageClassSpecLoc(), err);
874 else
875 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000876 // FIXME: It would be nicer if the keyword was ignored only for this
877 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000878 D.getMutableDeclSpec().ClearStorageClassSpecs();
879 }
880 }
881 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000882 default:
883 if (DS.getStorageClassSpecLoc().isValid())
884 Diag(DS.getStorageClassSpecLoc(),
885 diag::err_storageclass_invalid_for_member);
886 else
887 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
888 D.getMutableDeclSpec().ClearStorageClassSpecs();
889 }
890
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000891 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000892 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000893 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000894 // Check also for this case:
895 //
896 // typedef int f();
897 // f a;
898 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000899 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000900 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000901 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000902
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000903 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
904 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000905 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000906
907 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000908 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000909 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000910 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
911 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000912 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000913 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000914 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000915 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000916 if (!Member) {
917 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000918 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000919 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000920
921 // Non-instance-fields can't have a bitfield.
922 if (BitWidth) {
923 if (Member->isInvalidDecl()) {
924 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000925 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000926 // C++ 9.6p3: A bit-field shall not be a static member.
927 // "static member 'A' cannot be a bit-field"
928 Diag(Loc, diag::err_static_not_bitfield)
929 << Name << BitWidth->getSourceRange();
930 } else if (isa<TypedefDecl>(Member)) {
931 // "typedef member 'x' cannot be a bit-field"
932 Diag(Loc, diag::err_typedef_not_bitfield)
933 << Name << BitWidth->getSourceRange();
934 } else {
935 // A function typedef ("typedef int f(); f a;").
936 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
937 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000938 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000939 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattnerd26760a2009-03-05 23:01:03 +0000942 DeleteExpr(BitWidth);
943 BitWidth = 0;
944 Member->setInvalidDecl();
945 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000946
947 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000948
Douglas Gregor3447e762009-08-20 22:52:58 +0000949 // If we have declared a member function template, set the access of the
950 // templated declaration as well.
951 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
952 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000953 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000954
Douglas Gregor92751d42008-11-17 22:58:34 +0000955 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000956
Douglas Gregor0c880302009-03-11 23:00:04 +0000957 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000958 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000959 if (Deleted) // FIXME: Source location is not very good.
960 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000961
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000962 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000963 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000964 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000965 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000966 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000967}
968
Douglas Gregor15e77a22009-12-31 09:10:24 +0000969/// \brief Find the direct and/or virtual base specifiers that
970/// correspond to the given base type, for use in base initialization
971/// within a constructor.
972static bool FindBaseInitializer(Sema &SemaRef,
973 CXXRecordDecl *ClassDecl,
974 QualType BaseType,
975 const CXXBaseSpecifier *&DirectBaseSpec,
976 const CXXBaseSpecifier *&VirtualBaseSpec) {
977 // First, check for a direct base class.
978 DirectBaseSpec = 0;
979 for (CXXRecordDecl::base_class_const_iterator Base
980 = ClassDecl->bases_begin();
981 Base != ClassDecl->bases_end(); ++Base) {
982 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
983 // We found a direct base of this type. That's what we're
984 // initializing.
985 DirectBaseSpec = &*Base;
986 break;
987 }
988 }
989
990 // Check for a virtual base class.
991 // FIXME: We might be able to short-circuit this if we know in advance that
992 // there are no virtual bases.
993 VirtualBaseSpec = 0;
994 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
995 // We haven't found a base yet; search the class hierarchy for a
996 // virtual base class.
997 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
998 /*DetectVirtual=*/false);
999 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1000 BaseType, Paths)) {
1001 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1002 Path != Paths.end(); ++Path) {
1003 if (Path->back().Base->isVirtual()) {
1004 VirtualBaseSpec = Path->back().Base;
1005 break;
1006 }
1007 }
1008 }
1009 }
1010
1011 return DirectBaseSpec || VirtualBaseSpec;
1012}
1013
Douglas Gregore8381c02008-11-05 04:29:56 +00001014/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001015Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001016Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001017 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001018 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001019 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001020 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001021 SourceLocation IdLoc,
1022 SourceLocation LParenLoc,
1023 ExprTy **Args, unsigned NumArgs,
1024 SourceLocation *CommaLocs,
1025 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001026 if (!ConstructorD)
1027 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001029 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001030
1031 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001032 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001033 if (!Constructor) {
1034 // The user wrote a constructor initializer on a function that is
1035 // not a C++ constructor. Ignore the error for now, because we may
1036 // have more member initializers coming; we'll diagnose it just
1037 // once in ActOnMemInitializers.
1038 return true;
1039 }
1040
1041 CXXRecordDecl *ClassDecl = Constructor->getParent();
1042
1043 // C++ [class.base.init]p2:
1044 // Names in a mem-initializer-id are looked up in the scope of the
1045 // constructor’s class and, if not found in that scope, are looked
1046 // up in the scope containing the constructor’s
1047 // definition. [Note: if the constructor’s class contains a member
1048 // with the same name as a direct or virtual base class of the
1049 // class, a mem-initializer-id naming the member or base class and
1050 // composed of a single identifier refers to the class member. A
1051 // mem-initializer-id for the hidden base class may be specified
1052 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001053 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001054 // Look for a member, first.
1055 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001056 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001057 = ClassDecl->lookup(MemberOrBase);
1058 if (Result.first != Result.second)
1059 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001060
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001061 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001062
Eli Friedman8e1433b2009-07-29 19:44:27 +00001063 if (Member)
1064 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001065 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001066 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001067 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001068 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001069 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001070
1071 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001072 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001073 } else {
1074 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1075 LookupParsedName(R, S, &SS);
1076
1077 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1078 if (!TyD) {
1079 if (R.isAmbiguous()) return true;
1080
Douglas Gregora3b624a2010-01-19 06:46:48 +00001081 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1082 bool NotUnknownSpecialization = false;
1083 DeclContext *DC = computeDeclContext(SS, false);
1084 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1085 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1086
1087 if (!NotUnknownSpecialization) {
1088 // When the scope specifier can refer to a member of an unknown
1089 // specialization, we take it as a type name.
1090 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1091 *MemberOrBase, SS.getRange());
Douglas Gregor281c4862010-03-07 23:26:22 +00001092 if (BaseType.isNull())
1093 return true;
1094
Douglas Gregora3b624a2010-01-19 06:46:48 +00001095 R.clear();
1096 }
1097 }
1098
Douglas Gregor15e77a22009-12-31 09:10:24 +00001099 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001100 if (R.empty() && BaseType.isNull() &&
Douglas Gregor15e77a22009-12-31 09:10:24 +00001101 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1102 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1103 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1104 // We have found a non-static data member with a similar
1105 // name to what was typed; complain and initialize that
1106 // member.
1107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1108 << MemberOrBase << true << R.getLookupName()
1109 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1110 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001111 Diag(Member->getLocation(), diag::note_previous_decl)
1112 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001113
1114 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1115 LParenLoc, RParenLoc);
1116 }
1117 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1118 const CXXBaseSpecifier *DirectBaseSpec;
1119 const CXXBaseSpecifier *VirtualBaseSpec;
1120 if (FindBaseInitializer(*this, ClassDecl,
1121 Context.getTypeDeclType(Type),
1122 DirectBaseSpec, VirtualBaseSpec)) {
1123 // We have found a direct or virtual base class with a
1124 // similar name to what was typed; complain and initialize
1125 // that base class.
1126 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1127 << MemberOrBase << false << R.getLookupName()
1128 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1129 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001130
1131 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1132 : VirtualBaseSpec;
1133 Diag(BaseSpec->getSourceRange().getBegin(),
1134 diag::note_base_class_specified_here)
1135 << BaseSpec->getType()
1136 << BaseSpec->getSourceRange();
1137
Douglas Gregor15e77a22009-12-31 09:10:24 +00001138 TyD = Type;
1139 }
1140 }
1141 }
1142
Douglas Gregora3b624a2010-01-19 06:46:48 +00001143 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001144 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1145 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1146 return true;
1147 }
John McCallb5a0d312009-12-21 10:41:20 +00001148 }
1149
Douglas Gregora3b624a2010-01-19 06:46:48 +00001150 if (BaseType.isNull()) {
1151 BaseType = Context.getTypeDeclType(TyD);
1152 if (SS.isSet()) {
1153 NestedNameSpecifier *Qualifier =
1154 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001155
Douglas Gregora3b624a2010-01-19 06:46:48 +00001156 // FIXME: preserve source range information
1157 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1158 }
John McCallb5a0d312009-12-21 10:41:20 +00001159 }
1160 }
Mike Stump11289f42009-09-09 15:08:12 +00001161
John McCallbcd03502009-12-07 02:54:59 +00001162 if (!TInfo)
1163 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001164
John McCallbcd03502009-12-07 02:54:59 +00001165 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001166 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001167}
1168
John McCalle22a04a2009-11-04 23:02:40 +00001169/// Checks an initializer expression for use of uninitialized fields, such as
1170/// containing the field that is being initialized. Returns true if there is an
1171/// uninitialized field was used an updates the SourceLocation parameter; false
1172/// otherwise.
1173static bool InitExprContainsUninitializedFields(const Stmt* S,
1174 const FieldDecl* LhsField,
1175 SourceLocation* L) {
1176 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1177 if (ME) {
1178 const NamedDecl* RhsField = ME->getMemberDecl();
1179 if (RhsField == LhsField) {
1180 // Initializing a field with itself. Throw a warning.
1181 // But wait; there are exceptions!
1182 // Exception #1: The field may not belong to this record.
1183 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1184 const Expr* base = ME->getBase();
1185 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1186 // Even though the field matches, it does not belong to this record.
1187 return false;
1188 }
1189 // None of the exceptions triggered; return true to indicate an
1190 // uninitialized field was used.
1191 *L = ME->getMemberLoc();
1192 return true;
1193 }
1194 }
1195 bool found = false;
1196 for (Stmt::const_child_iterator it = S->child_begin();
1197 it != S->child_end() && found == false;
1198 ++it) {
1199 if (isa<CallExpr>(S)) {
1200 // Do not descend into function calls or constructors, as the use
1201 // of an uninitialized field may be valid. One would have to inspect
1202 // the contents of the function/ctor to determine if it is safe or not.
1203 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1204 // may be safe, depending on what the function/ctor does.
1205 continue;
1206 }
1207 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1208 }
1209 return found;
1210}
1211
Eli Friedman8e1433b2009-07-29 19:44:27 +00001212Sema::MemInitResult
1213Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1214 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001215 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001216 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001217 // Diagnose value-uses of fields to initialize themselves, e.g.
1218 // foo(foo)
1219 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001220 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001221 for (unsigned i = 0; i < NumArgs; ++i) {
1222 SourceLocation L;
1223 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1224 // FIXME: Return true in the case when other fields are used before being
1225 // uninitialized. For example, let this field be the i'th field. When
1226 // initializing the i'th field, throw a warning if any of the >= i'th
1227 // fields are used, as they are not yet initialized.
1228 // Right now we are only handling the case where the i'th field uses
1229 // itself in its initializer.
1230 Diag(L, diag::warn_field_is_uninit);
1231 }
1232 }
1233
Eli Friedman8e1433b2009-07-29 19:44:27 +00001234 bool HasDependentArg = false;
1235 for (unsigned i = 0; i < NumArgs; i++)
1236 HasDependentArg |= Args[i]->isTypeDependent();
1237
Eli Friedman8e1433b2009-07-29 19:44:27 +00001238 QualType FieldType = Member->getType();
1239 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1240 FieldType = Array->getElementType();
Eli Friedman11c7b152009-12-25 23:59:21 +00001241 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001242 if (FieldType->isDependentType() || HasDependentArg) {
1243 // Can't check initialization for a member of dependent type or when
1244 // any of the arguments are type-dependent expressions.
1245 OwningExprResult Init
1246 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1247 RParenLoc));
1248
1249 // Erase any temporaries within this evaluation context; we're not
1250 // going to track them in the AST, since we'll be rebuilding the
1251 // ASTs during template instantiation.
1252 ExprTemporaries.erase(
1253 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1254 ExprTemporaries.end());
1255
1256 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1257 LParenLoc,
1258 Init.takeAs<Expr>(),
1259 RParenLoc);
1260
Douglas Gregore8381c02008-11-05 04:29:56 +00001261 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001262
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001263 if (Member->isInvalidDecl())
1264 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001265
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001266 // Initialize the member.
1267 InitializedEntity MemberEntity =
1268 InitializedEntity::InitializeMember(Member, 0);
1269 InitializationKind Kind =
1270 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1271
1272 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1273
1274 OwningExprResult MemberInit =
1275 InitSeq.Perform(*this, MemberEntity, Kind,
1276 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1277 if (MemberInit.isInvalid())
1278 return true;
1279
1280 // C++0x [class.base.init]p7:
1281 // The initialization of each base and member constitutes a
1282 // full-expression.
1283 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1284 if (MemberInit.isInvalid())
1285 return true;
1286
1287 // If we are in a dependent context, template instantiation will
1288 // perform this type-checking again. Just save the arguments that we
1289 // received in a ParenListExpr.
1290 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1291 // of the information that we have about the member
1292 // initializer. However, deconstructing the ASTs is a dicey process,
1293 // and this approach is far more likely to get the corner cases right.
1294 if (CurContext->isDependentContext()) {
1295 // Bump the reference count of all of the arguments.
1296 for (unsigned I = 0; I != NumArgs; ++I)
1297 Args[I]->Retain();
1298
1299 OwningExprResult Init
1300 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1301 RParenLoc));
1302 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1303 LParenLoc,
1304 Init.takeAs<Expr>(),
1305 RParenLoc);
1306 }
1307
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001308 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001309 LParenLoc,
1310 MemberInit.takeAs<Expr>(),
1311 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001312}
1313
1314Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001315Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001316 Expr **Args, unsigned NumArgs,
1317 SourceLocation LParenLoc, SourceLocation RParenLoc,
1318 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001319 bool HasDependentArg = false;
1320 for (unsigned i = 0; i < NumArgs; i++)
1321 HasDependentArg |= Args[i]->isTypeDependent();
1322
John McCallbcd03502009-12-07 02:54:59 +00001323 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001324 if (BaseType->isDependentType() || HasDependentArg) {
1325 // Can't check initialization for a base of dependent type or when
1326 // any of the arguments are type-dependent expressions.
1327 OwningExprResult BaseInit
1328 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1329 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001330
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001331 // Erase any temporaries within this evaluation context; we're not
1332 // going to track them in the AST, since we'll be rebuilding the
1333 // ASTs during template instantiation.
1334 ExprTemporaries.erase(
1335 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1336 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001338 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1339 LParenLoc,
1340 BaseInit.takeAs<Expr>(),
1341 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001342 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001343
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001344 if (!BaseType->isRecordType())
1345 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1346 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1347
1348 // C++ [class.base.init]p2:
1349 // [...] Unless the mem-initializer-id names a nonstatic data
1350 // member of the constructor’s class or a direct or virtual base
1351 // of that class, the mem-initializer is ill-formed. A
1352 // mem-initializer-list can initialize a base class using any
1353 // name that denotes that base class type.
1354
1355 // Check for direct and virtual base classes.
1356 const CXXBaseSpecifier *DirectBaseSpec = 0;
1357 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1358 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1359 VirtualBaseSpec);
1360
1361 // C++ [base.class.init]p2:
1362 // If a mem-initializer-id is ambiguous because it designates both
1363 // a direct non-virtual base class and an inherited virtual base
1364 // class, the mem-initializer is ill-formed.
1365 if (DirectBaseSpec && VirtualBaseSpec)
1366 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1367 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1368 // C++ [base.class.init]p2:
1369 // Unless the mem-initializer-id names a nonstatic data membeer of the
1370 // constructor's class ot a direst or virtual base of that class, the
1371 // mem-initializer is ill-formed.
1372 if (!DirectBaseSpec && !VirtualBaseSpec)
1373 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1374 << BaseType << ClassDecl->getNameAsCString()
1375 << BaseTInfo->getTypeLoc().getSourceRange();
1376
1377 CXXBaseSpecifier *BaseSpec
1378 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1379 if (!BaseSpec)
1380 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1381
1382 // Initialize the base.
1383 InitializedEntity BaseEntity =
1384 InitializedEntity::InitializeBase(Context, BaseSpec);
1385 InitializationKind Kind =
1386 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1387
1388 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1389
1390 OwningExprResult BaseInit =
1391 InitSeq.Perform(*this, BaseEntity, Kind,
1392 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1393 if (BaseInit.isInvalid())
1394 return true;
1395
1396 // C++0x [class.base.init]p7:
1397 // The initialization of each base and member constitutes a
1398 // full-expression.
1399 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1400 if (BaseInit.isInvalid())
1401 return true;
1402
1403 // If we are in a dependent context, template instantiation will
1404 // perform this type-checking again. Just save the arguments that we
1405 // received in a ParenListExpr.
1406 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1407 // of the information that we have about the base
1408 // initializer. However, deconstructing the ASTs is a dicey process,
1409 // and this approach is far more likely to get the corner cases right.
1410 if (CurContext->isDependentContext()) {
1411 // Bump the reference count of all of the arguments.
1412 for (unsigned I = 0; I != NumArgs; ++I)
1413 Args[I]->Retain();
1414
1415 OwningExprResult Init
1416 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1417 RParenLoc));
1418 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1419 LParenLoc,
1420 Init.takeAs<Expr>(),
1421 RParenLoc);
1422 }
1423
1424 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1425 LParenLoc,
1426 BaseInit.takeAs<Expr>(),
1427 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001428}
1429
Eli Friedman9cf6b592009-11-09 19:20:36 +00001430bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001431Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001432 CXXBaseOrMemberInitializer **Initializers,
1433 unsigned NumInitializers,
1434 bool IsImplicitConstructor,
1435 bool AnyErrors) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001436 // We need to build the initializer AST according to order of construction
1437 // and not what user specified in the Initializers list.
1438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1439 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1440 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1441 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001442 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001443
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001444 for (unsigned i = 0; i < NumInitializers; i++) {
1445 CXXBaseOrMemberInitializer *Member = Initializers[i];
1446 if (Member->isBaseInitializer()) {
1447 if (Member->getBaseClass()->isDependentType())
1448 HasDependentBaseInit = true;
1449 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1450 } else {
1451 AllBaseFields[Member->getMember()] = Member;
1452 }
1453 }
Mike Stump11289f42009-09-09 15:08:12 +00001454
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001455 if (HasDependentBaseInit) {
1456 // FIXME. This does not preserve the ordering of the initializers.
1457 // Try (with -Wreorder)
1458 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001459 // template<class X> struct B : A<X> {
1460 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001461 // int x1;
1462 // };
1463 // B<int> x;
1464 // On seeing one dependent type, we should essentially exit this routine
1465 // while preserving user-declared initializer list. When this routine is
1466 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001467 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001468
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001469 // If we have a dependent base initialization, we can't determine the
1470 // association between initializers and bases; just dump the known
1471 // initializers into the list, and don't try to deal with other bases.
1472 for (unsigned i = 0; i < NumInitializers; i++) {
1473 CXXBaseOrMemberInitializer *Member = Initializers[i];
1474 if (Member->isBaseInitializer())
1475 AllToInit.push_back(Member);
1476 }
1477 } else {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001478 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1479
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001480 // Push virtual bases before others.
1481 for (CXXRecordDecl::base_class_iterator VBase =
1482 ClassDecl->vbases_begin(),
1483 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1484 if (VBase->getType()->isDependentType())
1485 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001486 if (CXXBaseOrMemberInitializer *Value
1487 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001488 AllToInit.push_back(Value);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001489 } else if (!AnyErrors) {
1490 InitializedEntity InitEntity
1491 = InitializedEntity::InitializeBase(Context, VBase);
1492 InitializationKind InitKind
1493 = InitializationKind::CreateDefault(Constructor->getLocation());
1494 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1495 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1496 MultiExprArg(*this, 0, 0));
1497 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1498 if (BaseInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001499 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001500 continue;
1501 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001502
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001503 // Don't attach synthesized base initializers in a dependent
1504 // context; they'll be checked again at template instantiation
1505 // time.
1506 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001507 continue;
1508
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001509 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001510 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001511 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001512 SourceLocation()),
Anders Carlsson561f7932009-10-29 15:46:07 +00001513 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001514 BaseInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001515 SourceLocation());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001516 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001517 }
1518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001520 for (CXXRecordDecl::base_class_iterator Base =
1521 ClassDecl->bases_begin(),
1522 E = ClassDecl->bases_end(); Base != E; ++Base) {
1523 // Virtuals are in the virtual base list and already constructed.
1524 if (Base->isVirtual())
1525 continue;
1526 // Skip dependent types.
1527 if (Base->getType()->isDependentType())
1528 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001529 if (CXXBaseOrMemberInitializer *Value
1530 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001531 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001532 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001533 else if (!AnyErrors) {
1534 InitializedEntity InitEntity
1535 = InitializedEntity::InitializeBase(Context, Base);
1536 InitializationKind InitKind
1537 = InitializationKind::CreateDefault(Constructor->getLocation());
1538 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1539 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1540 MultiExprArg(*this, 0, 0));
1541 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1542 if (BaseInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001543 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001544 continue;
1545 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001546
1547 // Don't attach synthesized base initializers in a dependent
1548 // context; they'll be regenerated at template instantiation
1549 // time.
1550 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001551 continue;
1552
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001553 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001554 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001555 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001556 SourceLocation()),
Anders Carlsson561f7932009-10-29 15:46:07 +00001557 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001558 BaseInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001559 SourceLocation());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001560 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001561 }
1562 }
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001565 // non-static data members.
1566 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1567 E = ClassDecl->field_end(); Field != E; ++Field) {
1568 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001569 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001570 Field->getType()->getAs<RecordType>()) {
1571 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001572 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001573 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001574 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1575 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1576 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1577 // set to the anonymous union data member used in the initializer
1578 // list.
1579 Value->setMember(*Field);
1580 Value->setAnonUnionMember(*FA);
1581 AllToInit.push_back(Value);
1582 break;
1583 }
1584 }
1585 }
1586 continue;
1587 }
1588 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1589 AllToInit.push_back(Value);
1590 continue;
1591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001593 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001594 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001595
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001596 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001597 if (FT->getAs<RecordType>()) {
1598 InitializedEntity InitEntity
1599 = InitializedEntity::InitializeMember(*Field);
1600 InitializationKind InitKind
1601 = InitializationKind::CreateDefault(Constructor->getLocation());
1602
1603 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1604 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1605 MultiExprArg(*this, 0, 0));
1606 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1607 if (MemberInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001608 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001609 continue;
1610 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001611
1612 // Don't attach synthesized member initializers in a dependent
1613 // context; they'll be regenerated a template instantiation
1614 // time.
1615 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001616 continue;
1617
Mike Stump11289f42009-09-09 15:08:12 +00001618 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001619 new (Context) CXXBaseOrMemberInitializer(Context,
1620 *Field, SourceLocation(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001621 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001622 MemberInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001623 SourceLocation());
1624
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001625 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001626 }
1627 else if (FT->isReferenceType()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001628 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001629 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1630 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001631 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001632 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001633 }
1634 else if (FT.isConstQualified()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001635 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001636 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1637 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001638 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001639 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001640 }
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001643 NumInitializers = AllToInit.size();
1644 if (NumInitializers > 0) {
1645 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1646 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1647 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001648
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001649 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola70e040d2010-03-02 21:28:26 +00001650 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1651 CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1652 baseOrMemberInitializers[Idx] = Member;
1653 if (!Member->isBaseInitializer())
1654 continue;
1655 const Type *BaseType = Member->getBaseClass();
1656 const RecordType *RT = BaseType->getAs<RecordType>();
1657 if (!RT)
1658 continue;
1659 CXXRecordDecl *BaseClassDecl =
1660 cast<CXXRecordDecl>(RT->getDecl());
1661 if (BaseClassDecl->hasTrivialDestructor())
1662 continue;
1663 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1664 MarkDeclarationReferenced(Constructor->getLocation(), DD);
1665 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001666 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001667
1668 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001669}
1670
Eli Friedman952c15d2009-07-21 19:28:10 +00001671static void *GetKeyForTopLevelField(FieldDecl *Field) {
1672 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001673 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001674 if (RT->getDecl()->isAnonymousStructOrUnion())
1675 return static_cast<void *>(RT->getDecl());
1676 }
1677 return static_cast<void *>(Field);
1678}
1679
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001680static void *GetKeyForBase(QualType BaseType) {
1681 if (const RecordType *RT = BaseType->getAs<RecordType>())
1682 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001683
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001684 assert(0 && "Unexpected base type!");
1685 return 0;
1686}
1687
Mike Stump11289f42009-09-09 15:08:12 +00001688static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001689 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001690 // For fields injected into the class via declaration of an anonymous union,
1691 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001692 if (Member->isMemberInitializer()) {
1693 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001694
Eli Friedmand7686ef2009-11-09 01:05:47 +00001695 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001696 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001697 // in AnonUnionMember field.
1698 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1699 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001700 if (Field->getDeclContext()->isRecord()) {
1701 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1702 if (RD->isAnonymousStructOrUnion())
1703 return static_cast<void *>(RD);
1704 }
1705 return static_cast<void *>(Field);
1706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001708 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001709}
1710
John McCallc90f6d72009-11-04 23:13:52 +00001711/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001712void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001713 SourceLocation ColonLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001714 MemInitTy **MemInits, unsigned NumMemInits,
1715 bool AnyErrors) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001716 if (!ConstructorDecl)
1717 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001718
1719 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001720
1721 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001722 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001723
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001724 if (!Constructor) {
1725 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1726 return;
1727 }
Mike Stump11289f42009-09-09 15:08:12 +00001728
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001729 if (!Constructor->isDependentContext()) {
1730 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1731 bool err = false;
1732 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001733 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001734 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1735 void *KeyToMember = GetKeyForMember(Member);
1736 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1737 if (!PrevMember) {
1738 PrevMember = Member;
1739 continue;
1740 }
1741 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001742 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001743 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001744 << Field->getNameAsString()
1745 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001746 else {
1747 Type *BaseClass = Member->getBaseClass();
1748 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001749 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001750 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001751 << QualType(BaseClass, 0)
1752 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001753 }
1754 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1755 << 0;
1756 err = true;
1757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001759 if (err)
1760 return;
1761 }
Mike Stump11289f42009-09-09 15:08:12 +00001762
Eli Friedmand7686ef2009-11-09 01:05:47 +00001763 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001764 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001765 NumMemInits, false, AnyErrors);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001767 if (Constructor->isDependentContext())
1768 return;
Mike Stump11289f42009-09-09 15:08:12 +00001769
1770 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001771 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001772 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001773 Diagnostic::Ignored)
1774 return;
Mike Stump11289f42009-09-09 15:08:12 +00001775
Anders Carlssone0eebb32009-08-27 05:45:01 +00001776 // Also issue warning if order of ctor-initializer list does not match order
1777 // of 1) base class declarations and 2) order of non-static data members.
1778 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Anders Carlssone0eebb32009-08-27 05:45:01 +00001780 CXXRecordDecl *ClassDecl
1781 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1782 // Push virtual bases before others.
1783 for (CXXRecordDecl::base_class_iterator VBase =
1784 ClassDecl->vbases_begin(),
1785 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001786 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001787
Anders Carlssone0eebb32009-08-27 05:45:01 +00001788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1789 E = ClassDecl->bases_end(); Base != E; ++Base) {
1790 // Virtuals are alread in the virtual base list and are constructed
1791 // first.
1792 if (Base->isVirtual())
1793 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001794 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001795 }
Mike Stump11289f42009-09-09 15:08:12 +00001796
Anders Carlssone0eebb32009-08-27 05:45:01 +00001797 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1798 E = ClassDecl->field_end(); Field != E; ++Field)
1799 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001800
Anders Carlssone0eebb32009-08-27 05:45:01 +00001801 int Last = AllBaseOrMembers.size();
1802 int curIndex = 0;
1803 CXXBaseOrMemberInitializer *PrevMember = 0;
1804 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001805 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001806 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1807 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001808
Anders Carlssone0eebb32009-08-27 05:45:01 +00001809 for (; curIndex < Last; curIndex++)
1810 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1811 break;
1812 if (curIndex == Last) {
1813 assert(PrevMember && "Member not in member list?!");
1814 // Initializer as specified in ctor-initializer list is out of order.
1815 // Issue a warning diagnostic.
1816 if (PrevMember->isBaseInitializer()) {
1817 // Diagnostics is for an initialized base class.
1818 Type *BaseClass = PrevMember->getBaseClass();
1819 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001820 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001821 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001822 } else {
1823 FieldDecl *Field = PrevMember->getMember();
1824 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001825 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001826 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001827 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001828 // Also the note!
1829 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001830 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001831 diag::note_fieldorbase_initialized_here) << 0
1832 << Field->getNameAsString();
1833 else {
1834 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001835 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001836 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001837 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001838 }
1839 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001840 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001841 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001842 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001843 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001844 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001845}
1846
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001847void
Anders Carlssondee9a302009-11-17 04:44:12 +00001848Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1849 // Ignore dependent destructors.
1850 if (Destructor->isDependentContext())
1851 return;
1852
1853 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001854
Anders Carlssondee9a302009-11-17 04:44:12 +00001855 // Non-static data members.
1856 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1857 E = ClassDecl->field_end(); I != E; ++I) {
1858 FieldDecl *Field = *I;
1859
1860 QualType FieldType = Context.getBaseElementType(Field->getType());
1861
1862 const RecordType* RT = FieldType->getAs<RecordType>();
1863 if (!RT)
1864 continue;
1865
1866 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1867 if (FieldClassDecl->hasTrivialDestructor())
1868 continue;
1869
1870 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1871 MarkDeclarationReferenced(Destructor->getLocation(),
1872 const_cast<CXXDestructorDecl*>(Dtor));
1873 }
1874
1875 // Bases.
1876 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1877 E = ClassDecl->bases_end(); Base != E; ++Base) {
1878 // Ignore virtual bases.
1879 if (Base->isVirtual())
1880 continue;
1881
1882 // Ignore trivial destructors.
1883 CXXRecordDecl *BaseClassDecl
1884 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1885 if (BaseClassDecl->hasTrivialDestructor())
1886 continue;
1887
1888 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1889 MarkDeclarationReferenced(Destructor->getLocation(),
1890 const_cast<CXXDestructorDecl*>(Dtor));
1891 }
1892
1893 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001894 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1895 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001896 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001897 CXXRecordDecl *BaseClassDecl
1898 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1899 if (BaseClassDecl->hasTrivialDestructor())
1900 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001901
1902 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1903 MarkDeclarationReferenced(Destructor->getLocation(),
1904 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001905 }
1906}
1907
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001908void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001909 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001910 return;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001912 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001913
1914 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001915 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001916 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001917}
1918
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001919namespace {
1920 /// PureVirtualMethodCollector - traverses a class and its superclasses
1921 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001922 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001923 ASTContext &Context;
1924
Sebastian Redlb7d64912009-03-22 21:28:55 +00001925 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001926 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001927
1928 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001929 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001931 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001933 public:
Mike Stump11289f42009-09-09 15:08:12 +00001934 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001935 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001936
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001937 MethodList List;
1938 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001939
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001940 // Copy the temporary list to methods, and make sure to ignore any
1941 // null entries.
1942 for (size_t i = 0, e = List.size(); i != e; ++i) {
1943 if (List[i])
1944 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001945 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001948 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001949
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001950 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1951 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001952 };
Mike Stump11289f42009-09-09 15:08:12 +00001953
1954 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001955 MethodList& Methods) {
1956 // First, collect the pure virtual methods for the base classes.
1957 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1958 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001959 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001960 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001961 if (BaseDecl && BaseDecl->isAbstract())
1962 Collect(BaseDecl, Methods);
1963 }
1964 }
Mike Stump11289f42009-09-09 15:08:12 +00001965
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001966 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001967 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001968
Anders Carlsson3c012712009-05-17 00:00:05 +00001969 MethodSetTy OverriddenMethods;
1970 size_t MethodsSize = Methods.size();
1971
Mike Stump11289f42009-09-09 15:08:12 +00001972 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001973 i != e; ++i) {
1974 // Traverse the record, looking for methods.
1975 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001976 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001977 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001978 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001979
Anders Carlsson700179432009-10-18 19:34:08 +00001980 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001981 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1982 E = MD->end_overridden_methods(); I != E; ++I) {
1983 // Keep track of the overridden methods.
1984 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001985 }
1986 }
1987 }
Mike Stump11289f42009-09-09 15:08:12 +00001988
1989 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001990 // overridden.
1991 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1992 if (OverriddenMethods.count(Methods[i]))
1993 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001994 }
Mike Stump11289f42009-09-09 15:08:12 +00001995
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001996 }
1997}
Douglas Gregore8381c02008-11-05 04:29:56 +00001998
Anders Carlssoneabf7702009-08-27 00:13:57 +00001999
Mike Stump11289f42009-09-09 15:08:12 +00002000bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002001 unsigned DiagID, AbstractDiagSelID SelID,
2002 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002003 if (SelID == -1)
2004 return RequireNonAbstractType(Loc, T,
2005 PDiag(DiagID), CurrentRD);
2006 else
2007 return RequireNonAbstractType(Loc, T,
2008 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002009}
2010
Anders Carlssoneabf7702009-08-27 00:13:57 +00002011bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2012 const PartialDiagnostic &PD,
2013 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002014 if (!getLangOptions().CPlusPlus)
2015 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002017 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002018 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002019 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002021 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002022 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002024 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002025
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002026 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002027 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002030 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002031 if (!RT)
2032 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCall67da35c2010-02-04 22:26:26 +00002034 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002035
Anders Carlssonb57738b2009-03-24 17:23:42 +00002036 if (CurrentRD && CurrentRD != RD)
2037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002038
John McCall67da35c2010-02-04 22:26:26 +00002039 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002040 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002041 return false;
2042
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002043 if (!RD->isAbstract())
2044 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002045
Anders Carlssoneabf7702009-08-27 00:13:57 +00002046 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002047
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002048 // Check if we've already emitted the list of pure virtual functions for this
2049 // class.
2050 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2051 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002052
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002053 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00002054
2055 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002056 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2057 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002058
2059 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002060 MD->getDeclName();
2061 }
2062
2063 if (!PureVirtualClassDiagSet)
2064 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2065 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002066
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002067 return true;
2068}
2069
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002070namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002071 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002072 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2073 Sema &SemaRef;
2074 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002075
Anders Carlssonb57738b2009-03-24 17:23:42 +00002076 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002077 bool Invalid = false;
2078
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002079 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2080 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002081 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002082
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002083 return Invalid;
2084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Anders Carlssonb57738b2009-03-24 17:23:42 +00002086 public:
2087 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2088 : SemaRef(SemaRef), AbstractClass(ac) {
2089 Visit(SemaRef.Context.getTranslationUnitDecl());
2090 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002091
Anders Carlssonb57738b2009-03-24 17:23:42 +00002092 bool VisitFunctionDecl(const FunctionDecl *FD) {
2093 if (FD->isThisDeclarationADefinition()) {
2094 // No need to do the check if we're in a definition, because it requires
2095 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002096 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002097 return VisitDeclContext(FD);
2098 }
Mike Stump11289f42009-09-09 15:08:12 +00002099
Anders Carlssonb57738b2009-03-24 17:23:42 +00002100 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002101 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002102 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002103 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2104 diag::err_abstract_type_in_decl,
2105 Sema::AbstractReturnType,
2106 AbstractClass);
2107
Mike Stump11289f42009-09-09 15:08:12 +00002108 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002109 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002110 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002111 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002112 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002113 VD->getOriginalType(),
2114 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002115 Sema::AbstractParamType,
2116 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002117 }
2118
2119 return Invalid;
2120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
Anders Carlssonb57738b2009-03-24 17:23:42 +00002122 bool VisitDecl(const Decl* D) {
2123 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2124 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Anders Carlssonb57738b2009-03-24 17:23:42 +00002126 return false;
2127 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002128 };
2129}
2130
Douglas Gregorc99f1552009-12-03 18:33:45 +00002131/// \brief Perform semantic checks on a class definition that has been
2132/// completing, introducing implicitly-declared members, checking for
2133/// abstract types, etc.
2134void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2135 if (!Record || Record->isInvalidDecl())
2136 return;
2137
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002138 if (!Record->isDependentType())
2139 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002140
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002141 if (Record->isInvalidDecl())
2142 return;
2143
John McCall2cb94162010-01-28 07:38:46 +00002144 // Set access bits correctly on the directly-declared conversions.
2145 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2146 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2147 Convs->setAccess(I, (*I)->getAccess());
2148
Douglas Gregorc99f1552009-12-03 18:33:45 +00002149 if (!Record->isAbstract()) {
2150 // Collect all the pure virtual methods and see if this is an abstract
2151 // class after all.
2152 PureVirtualMethodCollector Collector(Context, Record);
2153 if (!Collector.empty())
2154 Record->setAbstract(true);
2155 }
2156
2157 if (Record->isAbstract())
2158 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002159}
2160
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002161void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002162 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002163 SourceLocation LBrac,
2164 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002165 if (!TagDecl)
2166 return;
Mike Stump11289f42009-09-09 15:08:12 +00002167
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002168 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002169
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002170 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002171 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00002172 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00002173
Douglas Gregorc99f1552009-12-03 18:33:45 +00002174 CheckCompletedCXXClass(
2175 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002176}
2177
Douglas Gregor05379422008-11-03 17:51:48 +00002178/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2179/// special functions, such as the default constructor, copy
2180/// constructor, or destructor, to the given C++ class (C++
2181/// [special]p1). This routine can only be executed just before the
2182/// definition of the class is complete.
2183void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002184 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002185 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002186
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002187 // FIXME: Implicit declarations have exception specifications, which are
2188 // the union of the specifications of the implicitly called functions.
2189
Douglas Gregor05379422008-11-03 17:51:48 +00002190 if (!ClassDecl->hasUserDeclaredConstructor()) {
2191 // C++ [class.ctor]p5:
2192 // A default constructor for a class X is a constructor of class X
2193 // that can be called without an argument. If there is no
2194 // user-declared constructor for class X, a default constructor is
2195 // implicitly declared. An implicitly-declared default constructor
2196 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002197 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002198 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002199 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002200 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002201 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002202 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002203 0, 0, false, 0,
2204 /*FIXME*/false, false,
2205 0, 0, false,
2206 CC_Default),
John McCallbcd03502009-12-07 02:54:59 +00002207 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002208 /*isExplicit=*/false,
2209 /*isInline=*/true,
2210 /*isImplicitlyDeclared=*/true);
2211 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002212 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002213 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002214 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002215 }
2216
2217 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2218 // C++ [class.copy]p4:
2219 // If the class definition does not explicitly declare a copy
2220 // constructor, one is declared implicitly.
2221
2222 // C++ [class.copy]p5:
2223 // The implicitly-declared copy constructor for a class X will
2224 // have the form
2225 //
2226 // X::X(const X&)
2227 //
2228 // if
2229 bool HasConstCopyConstructor = true;
2230
2231 // -- each direct or virtual base class B of X has a copy
2232 // constructor whose first parameter is of type const B& or
2233 // const volatile B&, and
2234 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2235 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2236 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002237 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002238 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002239 = BaseClassDecl->hasConstCopyConstructor(Context);
2240 }
2241
2242 // -- for all the nonstatic data members of X that are of a
2243 // class type M (or array thereof), each such class type
2244 // has a copy constructor whose first parameter is of type
2245 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002246 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2247 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002248 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002249 QualType FieldType = (*Field)->getType();
2250 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2251 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002252 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002253 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002254 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002255 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002256 = FieldClassDecl->hasConstCopyConstructor(Context);
2257 }
2258 }
2259
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002260 // Otherwise, the implicitly declared copy constructor will have
2261 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002262 //
2263 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002264 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002265 if (HasConstCopyConstructor)
2266 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002267 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002268
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002269 // An implicitly-declared copy constructor is an inline public
2270 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002271 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002272 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002273 CXXConstructorDecl *CopyConstructor
2274 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002275 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002276 Context.getFunctionType(Context.VoidTy,
2277 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002278 false, 0,
2279 /*FIXME:*/false,
2280 false, 0, 0, false,
2281 CC_Default),
John McCallbcd03502009-12-07 02:54:59 +00002282 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002283 /*isExplicit=*/false,
2284 /*isInline=*/true,
2285 /*isImplicitlyDeclared=*/true);
2286 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002287 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002288 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002289
2290 // Add the parameter to the constructor.
2291 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2292 ClassDecl->getLocation(),
2293 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002294 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002295 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002296 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002297 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002298 }
2299
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002300 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2301 // Note: The following rules are largely analoguous to the copy
2302 // constructor rules. Note that virtual bases are not taken into account
2303 // for determining the argument type of the operator. Note also that
2304 // operators taking an object instead of a reference are allowed.
2305 //
2306 // C++ [class.copy]p10:
2307 // If the class definition does not explicitly declare a copy
2308 // assignment operator, one is declared implicitly.
2309 // The implicitly-defined copy assignment operator for a class X
2310 // will have the form
2311 //
2312 // X& X::operator=(const X&)
2313 //
2314 // if
2315 bool HasConstCopyAssignment = true;
2316
2317 // -- each direct base class B of X has a copy assignment operator
2318 // whose parameter is of type const B&, const volatile B& or B,
2319 // and
2320 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2321 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002322 assert(!Base->getType()->isDependentType() &&
2323 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002324 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002325 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002326 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002327 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002328 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002329 }
2330
2331 // -- for all the nonstatic data members of X that are of a class
2332 // type M (or array thereof), each such class type has a copy
2333 // assignment operator whose parameter is of type const M&,
2334 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002335 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2336 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002337 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002338 QualType FieldType = (*Field)->getType();
2339 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2340 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002341 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002342 const CXXRecordDecl *FieldClassDecl
2343 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002344 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002345 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002346 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002347 }
2348 }
2349
2350 // Otherwise, the implicitly declared copy assignment operator will
2351 // have the form
2352 //
2353 // X& X::operator=(X&)
2354 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002355 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002356 if (HasConstCopyAssignment)
2357 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002358 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002359
2360 // An implicitly-declared copy assignment operator is an inline public
2361 // member of its class.
2362 DeclarationName Name =
2363 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2364 CXXMethodDecl *CopyAssignment =
2365 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2366 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002367 false, 0,
2368 /*FIXME:*/false,
2369 false, 0, 0, false,
2370 CC_Default),
John McCallbcd03502009-12-07 02:54:59 +00002371 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002372 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002373 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002374 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002375 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002376
2377 // Add the parameter to the operator.
2378 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2379 ClassDecl->getLocation(),
2380 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002381 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002382 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002383 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002384
2385 // Don't call addedAssignmentOperator. There is no way to distinguish an
2386 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002387 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002388 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002389 }
2390
Douglas Gregor1349b452008-12-15 21:24:18 +00002391 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002392 // C++ [class.dtor]p2:
2393 // If a class has no user-declared destructor, a destructor is
2394 // declared implicitly. An implicitly-declared destructor is an
2395 // inline public member of its class.
John McCall58f10c32010-03-11 09:03:00 +00002396 QualType Ty = Context.getFunctionType(Context.VoidTy,
2397 0, 0, false, 0,
2398 /*FIXME:*/false,
2399 false, 0, 0, false,
2400 CC_Default);
2401
Mike Stump11289f42009-09-09 15:08:12 +00002402 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002403 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002404 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002405 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall58f10c32010-03-11 09:03:00 +00002406 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002407 /*isInline=*/true,
2408 /*isImplicitlyDeclared=*/true);
2409 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002410 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002411 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002412 ClassDecl->addDecl(Destructor);
John McCall58f10c32010-03-11 09:03:00 +00002413
2414 // This could be uniqued if it ever proves significant.
2415 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002416
2417 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002418 }
Douglas Gregor05379422008-11-03 17:51:48 +00002419}
2420
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002421void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002422 Decl *D = TemplateD.getAs<Decl>();
2423 if (!D)
2424 return;
2425
2426 TemplateParameterList *Params = 0;
2427 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2428 Params = Template->getTemplateParameters();
2429 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2430 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2431 Params = PartialSpec->getTemplateParameters();
2432 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002433 return;
2434
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002435 for (TemplateParameterList::iterator Param = Params->begin(),
2436 ParamEnd = Params->end();
2437 Param != ParamEnd; ++Param) {
2438 NamedDecl *Named = cast<NamedDecl>(*Param);
2439 if (Named->getDeclName()) {
2440 S->AddDecl(DeclPtrTy::make(Named));
2441 IdResolver.AddDecl(Named);
2442 }
2443 }
2444}
2445
John McCall6df5fef2009-12-19 10:49:29 +00002446void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2447 if (!RecordD) return;
2448 AdjustDeclIfTemplate(RecordD);
2449 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2450 PushDeclContext(S, Record);
2451}
2452
2453void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2454 if (!RecordD) return;
2455 PopDeclContext();
2456}
2457
Douglas Gregor4d87df52008-12-16 21:30:33 +00002458/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2459/// parsing a top-level (non-nested) C++ class, and we are now
2460/// parsing those parts of the given Method declaration that could
2461/// not be parsed earlier (C++ [class.mem]p2), such as default
2462/// arguments. This action should enter the scope of the given
2463/// Method declaration as if we had just parsed the qualified method
2464/// name. However, it should not bring the parameters into scope;
2465/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002466void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002467}
2468
2469/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2470/// C++ method declaration. We're (re-)introducing the given
2471/// function parameter into scope for use in parsing later parts of
2472/// the method declaration. For example, we could see an
2473/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002474void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002475 if (!ParamD)
2476 return;
Mike Stump11289f42009-09-09 15:08:12 +00002477
Chris Lattner83f095c2009-03-28 19:18:32 +00002478 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002479
2480 // If this parameter has an unparsed default argument, clear it out
2481 // to make way for the parsed default argument.
2482 if (Param->hasUnparsedDefaultArg())
2483 Param->setDefaultArg(0);
2484
Chris Lattner83f095c2009-03-28 19:18:32 +00002485 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002486 if (Param->getDeclName())
2487 IdResolver.AddDecl(Param);
2488}
2489
2490/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2491/// processing the delayed method declaration for Method. The method
2492/// declaration is now considered finished. There may be a separate
2493/// ActOnStartOfFunctionDef action later (not necessarily
2494/// immediately!) for this method, if it was also defined inside the
2495/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002496void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002497 if (!MethodD)
2498 return;
Mike Stump11289f42009-09-09 15:08:12 +00002499
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002500 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattner83f095c2009-03-28 19:18:32 +00002502 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002503
2504 // Now that we have our default arguments, check the constructor
2505 // again. It could produce additional diagnostics or affect whether
2506 // the class has implicitly-declared destructors, among other
2507 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002508 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2509 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002510
2511 // Check the default arguments, which we may have added.
2512 if (!Method->isInvalidDecl())
2513 CheckCXXDefaultArguments(Method);
2514}
2515
Douglas Gregor831c93f2008-11-05 20:51:48 +00002516/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002517/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002518/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002519/// emit diagnostics and set the invalid bit to true. In any case, the type
2520/// will be updated to reflect a well-formed type for the constructor and
2521/// returned.
2522QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2523 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002524 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002525
2526 // C++ [class.ctor]p3:
2527 // A constructor shall not be virtual (10.3) or static (9.4). A
2528 // constructor can be invoked for a const, volatile or const
2529 // volatile object. A constructor shall not be declared const,
2530 // volatile, or const volatile (9.3.2).
2531 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002532 if (!D.isInvalidType())
2533 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2534 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2535 << SourceRange(D.getIdentifierLoc());
2536 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002537 }
2538 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002539 if (!D.isInvalidType())
2540 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2541 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2542 << SourceRange(D.getIdentifierLoc());
2543 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002544 SC = FunctionDecl::None;
2545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Chris Lattner38378bf2009-04-25 08:28:21 +00002547 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2548 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002549 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002550 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2551 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002552 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002553 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2554 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002555 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002556 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2557 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregor831c93f2008-11-05 20:51:48 +00002560 // Rebuild the function type "R" without any type qualifiers (in
2561 // case any of the errors above fired) and with "void" as the
2562 // return type, since constructors don't have return types. We
2563 // *always* have to do this, because GetTypeForDeclarator will
2564 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002565 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002566 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2567 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002568 Proto->isVariadic(), 0,
2569 Proto->hasExceptionSpec(),
2570 Proto->hasAnyExceptionSpec(),
2571 Proto->getNumExceptions(),
2572 Proto->exception_begin(),
2573 Proto->getNoReturnAttr(),
2574 Proto->getCallConv());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002575}
2576
Douglas Gregor4d87df52008-12-16 21:30:33 +00002577/// CheckConstructor - Checks a fully-formed constructor for
2578/// well-formedness, issuing any diagnostics required. Returns true if
2579/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002580void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002582 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2583 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002584 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002585
2586 // C++ [class.copy]p3:
2587 // A declaration of a constructor for a class X is ill-formed if
2588 // its first parameter is of type (optionally cv-qualified) X and
2589 // either there are no other parameters or else all other
2590 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002591 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002592 ((Constructor->getNumParams() == 1) ||
2593 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002594 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2595 Constructor->getTemplateSpecializationKind()
2596 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002597 QualType ParamType = Constructor->getParamDecl(0)->getType();
2598 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2599 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002600 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2601 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002602 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002603
2604 // FIXME: Rather that making the constructor invalid, we should endeavor
2605 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002606 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002607 }
2608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609
Douglas Gregor4d87df52008-12-16 21:30:33 +00002610 // Notify the class that we've added a constructor.
2611 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002612}
2613
Anders Carlsson26a807d2009-11-30 21:24:50 +00002614/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2615/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002616bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002617 CXXRecordDecl *RD = Destructor->getParent();
2618
2619 if (Destructor->isVirtual()) {
2620 SourceLocation Loc;
2621
2622 if (!Destructor->isImplicit())
2623 Loc = Destructor->getLocation();
2624 else
2625 Loc = RD->getLocation();
2626
2627 // If we have a virtual destructor, look up the deallocation function
2628 FunctionDecl *OperatorDelete = 0;
2629 DeclarationName Name =
2630 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002631 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002632 return true;
2633
2634 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002635 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002636
2637 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002638}
2639
Mike Stump11289f42009-09-09 15:08:12 +00002640static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002641FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2642 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2643 FTI.ArgInfo[0].Param &&
2644 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2645}
2646
Douglas Gregor831c93f2008-11-05 20:51:48 +00002647/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2648/// the well-formednes of the destructor declarator @p D with type @p
2649/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002650/// emit diagnostics and set the declarator to invalid. Even if this happens,
2651/// will be updated to reflect a well-formed type for the destructor and
2652/// returned.
2653QualType Sema::CheckDestructorDeclarator(Declarator &D,
2654 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002655 // C++ [class.dtor]p1:
2656 // [...] A typedef-name that names a class is a class-name
2657 // (7.1.3); however, a typedef-name that names a class shall not
2658 // be used as the identifier in the declarator for a destructor
2659 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002660 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002661 if (isa<TypedefType>(DeclaratorType)) {
2662 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002663 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002664 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002665 }
2666
2667 // C++ [class.dtor]p2:
2668 // A destructor is used to destroy objects of its class type. A
2669 // destructor takes no parameters, and no return type can be
2670 // specified for it (not even void). The address of a destructor
2671 // shall not be taken. A destructor shall not be static. A
2672 // destructor can be invoked for a const, volatile or const
2673 // volatile object. A destructor shall not be declared const,
2674 // volatile or const volatile (9.3.2).
2675 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002676 if (!D.isInvalidType())
2677 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2678 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2679 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002680 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002681 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002682 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002683 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002684 // Destructors don't have return types, but the parser will
2685 // happily parse something like:
2686 //
2687 // class X {
2688 // float ~X();
2689 // };
2690 //
2691 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002692 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2693 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2694 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002695 }
Mike Stump11289f42009-09-09 15:08:12 +00002696
Chris Lattner38378bf2009-04-25 08:28:21 +00002697 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2698 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002699 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002700 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2701 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002702 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002703 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2704 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002705 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002706 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2707 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002708 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002709 }
2710
2711 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002712 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002713 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2714
2715 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002716 FTI.freeArgs();
2717 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002718 }
2719
Mike Stump11289f42009-09-09 15:08:12 +00002720 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002721 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002722 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002723 D.setInvalidType();
2724 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002725
2726 // Rebuild the function type "R" without any type qualifiers or
2727 // parameters (in case any of the errors above fired) and with
2728 // "void" as the return type, since destructors don't have return
2729 // types. We *always* have to do this, because GetTypeForDeclarator
2730 // will put in a result type of "int" when none was specified.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002731 // FIXME: Exceptions!
2732 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2733 false, false, 0, 0, false, CC_Default);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002734}
2735
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002736/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2737/// well-formednes of the conversion function declarator @p D with
2738/// type @p R. If there are any errors in the declarator, this routine
2739/// will emit diagnostics and return true. Otherwise, it will return
2740/// false. Either way, the type @p R will be updated to reflect a
2741/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002742void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002743 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002744 // C++ [class.conv.fct]p1:
2745 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002746 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002747 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002748 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002749 if (!D.isInvalidType())
2750 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2751 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2752 << SourceRange(D.getIdentifierLoc());
2753 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002754 SC = FunctionDecl::None;
2755 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002756 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002757 // Conversion functions don't have return types, but the parser will
2758 // happily parse something like:
2759 //
2760 // class X {
2761 // float operator bool();
2762 // };
2763 //
2764 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002765 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2766 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2767 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002768 }
2769
2770 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002771 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002772 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2773
2774 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002775 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002776 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002777 }
2778
Mike Stump11289f42009-09-09 15:08:12 +00002779 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002780 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002781 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002782 D.setInvalidType();
2783 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002784
2785 // C++ [class.conv.fct]p4:
2786 // The conversion-type-id shall not represent a function type nor
2787 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002788 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002789 if (ConvType->isArrayType()) {
2790 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2791 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002792 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002793 } else if (ConvType->isFunctionType()) {
2794 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2795 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002796 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002797 }
2798
2799 // Rebuild the function type "R" without any parameters (in case any
2800 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002801 // return type.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002802 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002803 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002804 Proto->getTypeQuals(),
2805 Proto->hasExceptionSpec(),
2806 Proto->hasAnyExceptionSpec(),
2807 Proto->getNumExceptions(),
2808 Proto->exception_begin(),
2809 Proto->getNoReturnAttr(),
2810 Proto->getCallConv());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002811
Douglas Gregor5fb53972009-01-14 15:45:31 +00002812 // C++0x explicit conversion operators.
2813 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002814 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002815 diag::warn_explicit_conversion_functions)
2816 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002817}
2818
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002819/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2820/// the declaration of the given C++ conversion function. This routine
2821/// is responsible for recording the conversion function in the C++
2822/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002823Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002824 assert(Conversion && "Expected to receive a conversion function declaration");
2825
Douglas Gregor4287b372008-12-12 08:25:50 +00002826 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002827
2828 // Make sure we aren't redeclaring the conversion function.
2829 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002830
2831 // C++ [class.conv.fct]p1:
2832 // [...] A conversion function is never used to convert a
2833 // (possibly cv-qualified) object to the (possibly cv-qualified)
2834 // same object type (or a reference to it), to a (possibly
2835 // cv-qualified) base class of that type (or a reference to it),
2836 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002837 // FIXME: Suppress this warning if the conversion function ends up being a
2838 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002839 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002840 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002841 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002842 ConvType = ConvTypeRef->getPointeeType();
2843 if (ConvType->isRecordType()) {
2844 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2845 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002846 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002847 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002848 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002849 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002850 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002851 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002852 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002853 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002854 }
2855
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002856 if (Conversion->getPrimaryTemplate()) {
2857 // ignore specializations
2858 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00002859 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00002860 = Conversion->getDescribedFunctionTemplate()) {
2861 if (ClassDecl->replaceConversion(
2862 ConversionTemplate->getPreviousDeclaration(),
2863 ConversionTemplate))
2864 return DeclPtrTy::make(ConversionTemplate);
2865 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2866 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00002867 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002868 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002869 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002870 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002871 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002872 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002873 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002874
Chris Lattner83f095c2009-03-28 19:18:32 +00002875 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002876}
2877
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002878//===----------------------------------------------------------------------===//
2879// Namespace Handling
2880//===----------------------------------------------------------------------===//
2881
2882/// ActOnStartNamespaceDef - This is called at the start of a namespace
2883/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002884Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2885 SourceLocation IdentLoc,
2886 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00002887 SourceLocation LBrace,
2888 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002889 NamespaceDecl *Namespc =
2890 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2891 Namespc->setLBracLoc(LBrace);
2892
2893 Scope *DeclRegionScope = NamespcScope->getParent();
2894
Anders Carlssona7bcade2010-02-07 01:09:23 +00002895 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2896
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002897 if (II) {
2898 // C++ [namespace.def]p2:
2899 // The identifier in an original-namespace-definition shall not have been
2900 // previously defined in the declarative region in which the
2901 // original-namespace-definition appears. The identifier in an
2902 // original-namespace-definition is the name of the namespace. Subsequently
2903 // in that declarative region, it is treated as an original-namespace-name.
2904
John McCall9f3059a2009-10-09 21:13:30 +00002905 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002906 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002907 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002908
Douglas Gregor91f84212008-12-11 16:49:14 +00002909 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2910 // This is an extended namespace definition.
2911 // Attach this namespace decl to the chain of extended namespace
2912 // definitions.
2913 OrigNS->setNextNamespace(Namespc);
2914 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002915
Mike Stump11289f42009-09-09 15:08:12 +00002916 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002917 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002918 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002919 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002920 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002921 } else if (PrevDecl) {
2922 // This is an invalid name redefinition.
2923 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2924 << Namespc->getDeclName();
2925 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2926 Namespc->setInvalidDecl();
2927 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002928 } else if (II->isStr("std") &&
2929 CurContext->getLookupContext()->isTranslationUnit()) {
2930 // This is the first "real" definition of the namespace "std", so update
2931 // our cache of the "std" namespace to point at this definition.
2932 if (StdNamespace) {
2933 // We had already defined a dummy namespace "std". Link this new
2934 // namespace definition to the dummy namespace "std".
2935 StdNamespace->setNextNamespace(Namespc);
2936 StdNamespace->setLocation(IdentLoc);
2937 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2938 }
2939
2940 // Make our StdNamespace cache point at the first real definition of the
2941 // "std" namespace.
2942 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002943 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002944
2945 PushOnScopeChains(Namespc, DeclRegionScope);
2946 } else {
John McCall4fa53422009-10-01 00:25:31 +00002947 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00002948 assert(Namespc->isAnonymousNamespace());
2949 CurContext->addDecl(Namespc);
2950
2951 // Link the anonymous namespace into its parent.
2952 NamespaceDecl *PrevDecl;
2953 DeclContext *Parent = CurContext->getLookupContext();
2954 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2955 PrevDecl = TU->getAnonymousNamespace();
2956 TU->setAnonymousNamespace(Namespc);
2957 } else {
2958 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2959 PrevDecl = ND->getAnonymousNamespace();
2960 ND->setAnonymousNamespace(Namespc);
2961 }
2962
2963 // Link the anonymous namespace with its previous declaration.
2964 if (PrevDecl) {
2965 assert(PrevDecl->isAnonymousNamespace());
2966 assert(!PrevDecl->getNextNamespace());
2967 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2968 PrevDecl->setNextNamespace(Namespc);
2969 }
John McCall4fa53422009-10-01 00:25:31 +00002970
2971 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2972 // behaves as if it were replaced by
2973 // namespace unique { /* empty body */ }
2974 // using namespace unique;
2975 // namespace unique { namespace-body }
2976 // where all occurrences of 'unique' in a translation unit are
2977 // replaced by the same identifier and this identifier differs
2978 // from all other identifiers in the entire program.
2979
2980 // We just create the namespace with an empty name and then add an
2981 // implicit using declaration, just like the standard suggests.
2982 //
2983 // CodeGen enforces the "universally unique" aspect by giving all
2984 // declarations semantically contained within an anonymous
2985 // namespace internal linkage.
2986
John McCall0db42252009-12-16 02:06:49 +00002987 if (!PrevDecl) {
2988 UsingDirectiveDecl* UD
2989 = UsingDirectiveDecl::Create(Context, CurContext,
2990 /* 'using' */ LBrace,
2991 /* 'namespace' */ SourceLocation(),
2992 /* qualifier */ SourceRange(),
2993 /* NNS */ NULL,
2994 /* identifier */ SourceLocation(),
2995 Namespc,
2996 /* Ancestor */ CurContext);
2997 UD->setImplicit();
2998 CurContext->addDecl(UD);
2999 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003000 }
3001
3002 // Although we could have an invalid decl (i.e. the namespace name is a
3003 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003004 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3005 // for the namespace has the declarations that showed up in that particular
3006 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003007 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003008 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003009}
3010
Sebastian Redla6602e92009-11-23 15:34:23 +00003011/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3012/// is a namespace alias, returns the namespace it points to.
3013static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3014 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3015 return AD->getNamespace();
3016 return dyn_cast_or_null<NamespaceDecl>(D);
3017}
3018
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003019/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3020/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003021void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3022 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003023 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3024 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3025 Namespc->setRBracLoc(RBrace);
3026 PopDeclContext();
3027}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003028
Chris Lattner83f095c2009-03-28 19:18:32 +00003029Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3030 SourceLocation UsingLoc,
3031 SourceLocation NamespcLoc,
3032 const CXXScopeSpec &SS,
3033 SourceLocation IdentLoc,
3034 IdentifierInfo *NamespcName,
3035 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003036 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3037 assert(NamespcName && "Invalid NamespcName.");
3038 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003039 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003040
Douglas Gregor889ceb72009-02-03 19:21:40 +00003041 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003042
Douglas Gregor34074322009-01-14 22:20:51 +00003043 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003044 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3045 LookupParsedName(R, S, &SS);
3046 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003047 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003048
John McCall9f3059a2009-10-09 21:13:30 +00003049 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003050 NamedDecl *Named = R.getFoundDecl();
3051 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3052 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003053 // C++ [namespace.udir]p1:
3054 // A using-directive specifies that the names in the nominated
3055 // namespace can be used in the scope in which the
3056 // using-directive appears after the using-directive. During
3057 // unqualified name lookup (3.4.1), the names appear as if they
3058 // were declared in the nearest enclosing namespace which
3059 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003060 // namespace. [Note: in this context, "contains" means "contains
3061 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003062
3063 // Find enclosing context containing both using-directive and
3064 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003065 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003066 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3067 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3068 CommonAncestor = CommonAncestor->getParent();
3069
Sebastian Redla6602e92009-11-23 15:34:23 +00003070 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003071 SS.getRange(),
3072 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003073 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003074 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003075 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003076 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003077 }
3078
Douglas Gregor889ceb72009-02-03 19:21:40 +00003079 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003080 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003081 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003082}
3083
3084void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3085 // If scope has associated entity, then using directive is at namespace
3086 // or translation unit scope. We add UsingDirectiveDecls, into
3087 // it's lookup structure.
3088 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003089 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003090 else
3091 // Otherwise it is block-sope. using-directives will affect lookup
3092 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003093 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003094}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003095
Douglas Gregorfec52632009-06-20 00:51:54 +00003096
3097Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003098 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003099 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003100 SourceLocation UsingLoc,
3101 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003102 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003103 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003104 bool IsTypeName,
3105 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003106 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003107
Douglas Gregor220f4272009-11-04 16:30:06 +00003108 switch (Name.getKind()) {
3109 case UnqualifiedId::IK_Identifier:
3110 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003111 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003112 case UnqualifiedId::IK_ConversionFunctionId:
3113 break;
3114
3115 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003116 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003117 // C++0x inherited constructors.
3118 if (getLangOptions().CPlusPlus0x) break;
3119
Douglas Gregor220f4272009-11-04 16:30:06 +00003120 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3121 << SS.getRange();
3122 return DeclPtrTy();
3123
3124 case UnqualifiedId::IK_DestructorName:
3125 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3126 << SS.getRange();
3127 return DeclPtrTy();
3128
3129 case UnqualifiedId::IK_TemplateId:
3130 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3131 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3132 return DeclPtrTy();
3133 }
3134
3135 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003136 if (!TargetName)
3137 return DeclPtrTy();
3138
John McCalla0097262009-12-11 02:10:03 +00003139 // Warn about using declarations.
3140 // TODO: store that the declaration was written without 'using' and
3141 // talk about access decls instead of using decls in the
3142 // diagnostics.
3143 if (!HasUsingKeyword) {
3144 UsingLoc = Name.getSourceRange().getBegin();
3145
3146 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3147 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3148 "using ");
3149 }
3150
John McCall3f746822009-11-17 05:59:44 +00003151 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003152 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003153 TargetName, AttrList,
3154 /* IsInstantiation */ false,
3155 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003156 if (UD)
3157 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003158
Anders Carlsson696a3f12009-08-28 05:40:36 +00003159 return DeclPtrTy::make(UD);
3160}
3161
John McCall84d87672009-12-10 09:41:52 +00003162/// Determines whether to create a using shadow decl for a particular
3163/// decl, given the set of decls existing prior to this using lookup.
3164bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3165 const LookupResult &Previous) {
3166 // Diagnose finding a decl which is not from a base class of the
3167 // current class. We do this now because there are cases where this
3168 // function will silently decide not to build a shadow decl, which
3169 // will pre-empt further diagnostics.
3170 //
3171 // We don't need to do this in C++0x because we do the check once on
3172 // the qualifier.
3173 //
3174 // FIXME: diagnose the following if we care enough:
3175 // struct A { int foo; };
3176 // struct B : A { using A::foo; };
3177 // template <class T> struct C : A {};
3178 // template <class T> struct D : C<T> { using B::foo; } // <---
3179 // This is invalid (during instantiation) in C++03 because B::foo
3180 // resolves to the using decl in B, which is not a base class of D<T>.
3181 // We can't diagnose it immediately because C<T> is an unknown
3182 // specialization. The UsingShadowDecl in D<T> then points directly
3183 // to A::foo, which will look well-formed when we instantiate.
3184 // The right solution is to not collapse the shadow-decl chain.
3185 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3186 DeclContext *OrigDC = Orig->getDeclContext();
3187
3188 // Handle enums and anonymous structs.
3189 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3190 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3191 while (OrigRec->isAnonymousStructOrUnion())
3192 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3193
3194 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3195 if (OrigDC == CurContext) {
3196 Diag(Using->getLocation(),
3197 diag::err_using_decl_nested_name_specifier_is_current_class)
3198 << Using->getNestedNameRange();
3199 Diag(Orig->getLocation(), diag::note_using_decl_target);
3200 return true;
3201 }
3202
3203 Diag(Using->getNestedNameRange().getBegin(),
3204 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3205 << Using->getTargetNestedNameDecl()
3206 << cast<CXXRecordDecl>(CurContext)
3207 << Using->getNestedNameRange();
3208 Diag(Orig->getLocation(), diag::note_using_decl_target);
3209 return true;
3210 }
3211 }
3212
3213 if (Previous.empty()) return false;
3214
3215 NamedDecl *Target = Orig;
3216 if (isa<UsingShadowDecl>(Target))
3217 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3218
John McCalla17e83e2009-12-11 02:33:26 +00003219 // If the target happens to be one of the previous declarations, we
3220 // don't have a conflict.
3221 //
3222 // FIXME: but we might be increasing its access, in which case we
3223 // should redeclare it.
3224 NamedDecl *NonTag = 0, *Tag = 0;
3225 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3226 I != E; ++I) {
3227 NamedDecl *D = (*I)->getUnderlyingDecl();
3228 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3229 return false;
3230
3231 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3232 }
3233
John McCall84d87672009-12-10 09:41:52 +00003234 if (Target->isFunctionOrFunctionTemplate()) {
3235 FunctionDecl *FD;
3236 if (isa<FunctionTemplateDecl>(Target))
3237 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3238 else
3239 FD = cast<FunctionDecl>(Target);
3240
3241 NamedDecl *OldDecl = 0;
3242 switch (CheckOverload(FD, Previous, OldDecl)) {
3243 case Ovl_Overload:
3244 return false;
3245
3246 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003247 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003248 break;
3249
3250 // We found a decl with the exact signature.
3251 case Ovl_Match:
3252 if (isa<UsingShadowDecl>(OldDecl)) {
3253 // Silently ignore the possible conflict.
3254 return false;
3255 }
3256
3257 // If we're in a record, we want to hide the target, so we
3258 // return true (without a diagnostic) to tell the caller not to
3259 // build a shadow decl.
3260 if (CurContext->isRecord())
3261 return true;
3262
3263 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003264 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003265 break;
3266 }
3267
3268 Diag(Target->getLocation(), diag::note_using_decl_target);
3269 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3270 return true;
3271 }
3272
3273 // Target is not a function.
3274
John McCall84d87672009-12-10 09:41:52 +00003275 if (isa<TagDecl>(Target)) {
3276 // No conflict between a tag and a non-tag.
3277 if (!Tag) return false;
3278
John McCalle29c5cd2009-12-10 19:51:03 +00003279 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003280 Diag(Target->getLocation(), diag::note_using_decl_target);
3281 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3282 return true;
3283 }
3284
3285 // No conflict between a tag and a non-tag.
3286 if (!NonTag) return false;
3287
John McCalle29c5cd2009-12-10 19:51:03 +00003288 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003289 Diag(Target->getLocation(), diag::note_using_decl_target);
3290 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3291 return true;
3292}
3293
John McCall3f746822009-11-17 05:59:44 +00003294/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003295UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003296 UsingDecl *UD,
3297 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003298
3299 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003300 NamedDecl *Target = Orig;
3301 if (isa<UsingShadowDecl>(Target)) {
3302 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3303 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003304 }
3305
3306 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003307 = UsingShadowDecl::Create(Context, CurContext,
3308 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003309 UD->addShadowDecl(Shadow);
3310
3311 if (S)
John McCall3969e302009-12-08 07:46:18 +00003312 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003313 else
John McCall3969e302009-12-08 07:46:18 +00003314 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003315 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003316
John McCall3969e302009-12-08 07:46:18 +00003317 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3318 Shadow->setInvalidDecl();
3319
John McCall84d87672009-12-10 09:41:52 +00003320 return Shadow;
3321}
John McCall3969e302009-12-08 07:46:18 +00003322
John McCall84d87672009-12-10 09:41:52 +00003323/// Hides a using shadow declaration. This is required by the current
3324/// using-decl implementation when a resolvable using declaration in a
3325/// class is followed by a declaration which would hide or override
3326/// one or more of the using decl's targets; for example:
3327///
3328/// struct Base { void foo(int); };
3329/// struct Derived : Base {
3330/// using Base::foo;
3331/// void foo(int);
3332/// };
3333///
3334/// The governing language is C++03 [namespace.udecl]p12:
3335///
3336/// When a using-declaration brings names from a base class into a
3337/// derived class scope, member functions in the derived class
3338/// override and/or hide member functions with the same name and
3339/// parameter types in a base class (rather than conflicting).
3340///
3341/// There are two ways to implement this:
3342/// (1) optimistically create shadow decls when they're not hidden
3343/// by existing declarations, or
3344/// (2) don't create any shadow decls (or at least don't make them
3345/// visible) until we've fully parsed/instantiated the class.
3346/// The problem with (1) is that we might have to retroactively remove
3347/// a shadow decl, which requires several O(n) operations because the
3348/// decl structures are (very reasonably) not designed for removal.
3349/// (2) avoids this but is very fiddly and phase-dependent.
3350void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3351 // Remove it from the DeclContext...
3352 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003353
John McCall84d87672009-12-10 09:41:52 +00003354 // ...and the scope, if applicable...
3355 if (S) {
3356 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3357 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003358 }
3359
John McCall84d87672009-12-10 09:41:52 +00003360 // ...and the using decl.
3361 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3362
3363 // TODO: complain somehow if Shadow was used. It shouldn't
3364 // be possible for this to happen, because
John McCall3f746822009-11-17 05:59:44 +00003365}
3366
John McCalle61f2ba2009-11-18 02:36:19 +00003367/// Builds a using declaration.
3368///
3369/// \param IsInstantiation - Whether this call arises from an
3370/// instantiation of an unresolved using declaration. We treat
3371/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003372NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3373 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003374 const CXXScopeSpec &SS,
3375 SourceLocation IdentLoc,
3376 DeclarationName Name,
3377 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003378 bool IsInstantiation,
3379 bool IsTypeName,
3380 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003381 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3382 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003383
Anders Carlssonf038fc22009-08-28 05:49:21 +00003384 // FIXME: We ignore attributes for now.
3385 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003386
Anders Carlsson59140b32009-08-28 03:16:11 +00003387 if (SS.isEmpty()) {
3388 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003389 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
John McCall84d87672009-12-10 09:41:52 +00003392 // Do the redeclaration lookup in the current scope.
3393 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3394 ForRedeclaration);
3395 Previous.setHideTags(false);
3396 if (S) {
3397 LookupName(Previous, S);
3398
3399 // It is really dumb that we have to do this.
3400 LookupResult::Filter F = Previous.makeFilter();
3401 while (F.hasNext()) {
3402 NamedDecl *D = F.next();
3403 if (!isDeclInScope(D, CurContext, S))
3404 F.erase();
3405 }
3406 F.done();
3407 } else {
3408 assert(IsInstantiation && "no scope in non-instantiation");
3409 assert(CurContext->isRecord() && "scope not record in instantiation");
3410 LookupQualifiedName(Previous, CurContext);
3411 }
3412
Mike Stump11289f42009-09-09 15:08:12 +00003413 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003414 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3415
John McCall84d87672009-12-10 09:41:52 +00003416 // Check for invalid redeclarations.
3417 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3418 return 0;
3419
3420 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003421 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3422 return 0;
3423
John McCall84c16cf2009-11-12 03:15:40 +00003424 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003425 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003426 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003427 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003428 // FIXME: not all declaration name kinds are legal here
3429 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3430 UsingLoc, TypenameLoc,
3431 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003432 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003433 } else {
3434 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3435 UsingLoc, SS.getRange(), NNS,
3436 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003437 }
John McCallb96ec562009-12-04 22:46:56 +00003438 } else {
3439 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3440 SS.getRange(), UsingLoc, NNS, Name,
3441 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003442 }
John McCallb96ec562009-12-04 22:46:56 +00003443 D->setAccess(AS);
3444 CurContext->addDecl(D);
3445
3446 if (!LookupContext) return D;
3447 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003448
John McCall3969e302009-12-08 07:46:18 +00003449 if (RequireCompleteDeclContext(SS)) {
3450 UD->setInvalidDecl();
3451 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003452 }
3453
John McCall3969e302009-12-08 07:46:18 +00003454 // Look up the target name.
3455
John McCall27b18f82009-11-17 02:14:36 +00003456 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003457
John McCall3969e302009-12-08 07:46:18 +00003458 // Unlike most lookups, we don't always want to hide tag
3459 // declarations: tag names are visible through the using declaration
3460 // even if hidden by ordinary names, *except* in a dependent context
3461 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003462 if (!IsInstantiation)
3463 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003464
John McCall27b18f82009-11-17 02:14:36 +00003465 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003466
John McCall9f3059a2009-10-09 21:13:30 +00003467 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003468 Diag(IdentLoc, diag::err_no_member)
3469 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003470 UD->setInvalidDecl();
3471 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003472 }
3473
John McCallb96ec562009-12-04 22:46:56 +00003474 if (R.isAmbiguous()) {
3475 UD->setInvalidDecl();
3476 return UD;
3477 }
Mike Stump11289f42009-09-09 15:08:12 +00003478
John McCalle61f2ba2009-11-18 02:36:19 +00003479 if (IsTypeName) {
3480 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003481 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003482 Diag(IdentLoc, diag::err_using_typename_non_type);
3483 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3484 Diag((*I)->getUnderlyingDecl()->getLocation(),
3485 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003486 UD->setInvalidDecl();
3487 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003488 }
3489 } else {
3490 // If we asked for a non-typename and we got a type, error out,
3491 // but only if this is an instantiation of an unresolved using
3492 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003493 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003494 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3495 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003496 UD->setInvalidDecl();
3497 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003498 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003499 }
3500
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003501 // C++0x N2914 [namespace.udecl]p6:
3502 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003503 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003504 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3505 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003506 UD->setInvalidDecl();
3507 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003508 }
Mike Stump11289f42009-09-09 15:08:12 +00003509
John McCall84d87672009-12-10 09:41:52 +00003510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3511 if (!CheckUsingShadowDecl(UD, *I, Previous))
3512 BuildUsingShadowDecl(S, UD, *I);
3513 }
John McCall3f746822009-11-17 05:59:44 +00003514
3515 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003516}
3517
John McCall84d87672009-12-10 09:41:52 +00003518/// Checks that the given using declaration is not an invalid
3519/// redeclaration. Note that this is checking only for the using decl
3520/// itself, not for any ill-formedness among the UsingShadowDecls.
3521bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3522 bool isTypeName,
3523 const CXXScopeSpec &SS,
3524 SourceLocation NameLoc,
3525 const LookupResult &Prev) {
3526 // C++03 [namespace.udecl]p8:
3527 // C++0x [namespace.udecl]p10:
3528 // A using-declaration is a declaration and can therefore be used
3529 // repeatedly where (and only where) multiple declarations are
3530 // allowed.
3531 // That's only in file contexts.
3532 if (CurContext->getLookupContext()->isFileContext())
3533 return false;
3534
3535 NestedNameSpecifier *Qual
3536 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3537
3538 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3539 NamedDecl *D = *I;
3540
3541 bool DTypename;
3542 NestedNameSpecifier *DQual;
3543 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3544 DTypename = UD->isTypeName();
3545 DQual = UD->getTargetNestedNameDecl();
3546 } else if (UnresolvedUsingValueDecl *UD
3547 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3548 DTypename = false;
3549 DQual = UD->getTargetNestedNameSpecifier();
3550 } else if (UnresolvedUsingTypenameDecl *UD
3551 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3552 DTypename = true;
3553 DQual = UD->getTargetNestedNameSpecifier();
3554 } else continue;
3555
3556 // using decls differ if one says 'typename' and the other doesn't.
3557 // FIXME: non-dependent using decls?
3558 if (isTypeName != DTypename) continue;
3559
3560 // using decls differ if they name different scopes (but note that
3561 // template instantiation can cause this check to trigger when it
3562 // didn't before instantiation).
3563 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3564 Context.getCanonicalNestedNameSpecifier(DQual))
3565 continue;
3566
3567 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003568 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003569 return true;
3570 }
3571
3572 return false;
3573}
3574
John McCall3969e302009-12-08 07:46:18 +00003575
John McCallb96ec562009-12-04 22:46:56 +00003576/// Checks that the given nested-name qualifier used in a using decl
3577/// in the current context is appropriately related to the current
3578/// scope. If an error is found, diagnoses it and returns true.
3579bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3580 const CXXScopeSpec &SS,
3581 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003582 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003583
John McCall3969e302009-12-08 07:46:18 +00003584 if (!CurContext->isRecord()) {
3585 // C++03 [namespace.udecl]p3:
3586 // C++0x [namespace.udecl]p8:
3587 // A using-declaration for a class member shall be a member-declaration.
3588
3589 // If we weren't able to compute a valid scope, it must be a
3590 // dependent class scope.
3591 if (!NamedContext || NamedContext->isRecord()) {
3592 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3593 << SS.getRange();
3594 return true;
3595 }
3596
3597 // Otherwise, everything is known to be fine.
3598 return false;
3599 }
3600
3601 // The current scope is a record.
3602
3603 // If the named context is dependent, we can't decide much.
3604 if (!NamedContext) {
3605 // FIXME: in C++0x, we can diagnose if we can prove that the
3606 // nested-name-specifier does not refer to a base class, which is
3607 // still possible in some cases.
3608
3609 // Otherwise we have to conservatively report that things might be
3610 // okay.
3611 return false;
3612 }
3613
3614 if (!NamedContext->isRecord()) {
3615 // Ideally this would point at the last name in the specifier,
3616 // but we don't have that level of source info.
3617 Diag(SS.getRange().getBegin(),
3618 diag::err_using_decl_nested_name_specifier_is_not_class)
3619 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3620 return true;
3621 }
3622
3623 if (getLangOptions().CPlusPlus0x) {
3624 // C++0x [namespace.udecl]p3:
3625 // In a using-declaration used as a member-declaration, the
3626 // nested-name-specifier shall name a base class of the class
3627 // being defined.
3628
3629 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3630 cast<CXXRecordDecl>(NamedContext))) {
3631 if (CurContext == NamedContext) {
3632 Diag(NameLoc,
3633 diag::err_using_decl_nested_name_specifier_is_current_class)
3634 << SS.getRange();
3635 return true;
3636 }
3637
3638 Diag(SS.getRange().getBegin(),
3639 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3640 << (NestedNameSpecifier*) SS.getScopeRep()
3641 << cast<CXXRecordDecl>(CurContext)
3642 << SS.getRange();
3643 return true;
3644 }
3645
3646 return false;
3647 }
3648
3649 // C++03 [namespace.udecl]p4:
3650 // A using-declaration used as a member-declaration shall refer
3651 // to a member of a base class of the class being defined [etc.].
3652
3653 // Salient point: SS doesn't have to name a base class as long as
3654 // lookup only finds members from base classes. Therefore we can
3655 // diagnose here only if we can prove that that can't happen,
3656 // i.e. if the class hierarchies provably don't intersect.
3657
3658 // TODO: it would be nice if "definitely valid" results were cached
3659 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3660 // need to be repeated.
3661
3662 struct UserData {
3663 llvm::DenseSet<const CXXRecordDecl*> Bases;
3664
3665 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3666 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3667 Data->Bases.insert(Base);
3668 return true;
3669 }
3670
3671 bool hasDependentBases(const CXXRecordDecl *Class) {
3672 return !Class->forallBases(collect, this);
3673 }
3674
3675 /// Returns true if the base is dependent or is one of the
3676 /// accumulated base classes.
3677 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3678 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3679 return !Data->Bases.count(Base);
3680 }
3681
3682 bool mightShareBases(const CXXRecordDecl *Class) {
3683 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3684 }
3685 };
3686
3687 UserData Data;
3688
3689 // Returns false if we find a dependent base.
3690 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3691 return false;
3692
3693 // Returns false if the class has a dependent base or if it or one
3694 // of its bases is present in the base set of the current context.
3695 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3696 return false;
3697
3698 Diag(SS.getRange().getBegin(),
3699 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3700 << (NestedNameSpecifier*) SS.getScopeRep()
3701 << cast<CXXRecordDecl>(CurContext)
3702 << SS.getRange();
3703
3704 return true;
John McCallb96ec562009-12-04 22:46:56 +00003705}
3706
Mike Stump11289f42009-09-09 15:08:12 +00003707Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003708 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003709 SourceLocation AliasLoc,
3710 IdentifierInfo *Alias,
3711 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003712 SourceLocation IdentLoc,
3713 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003714
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003715 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003716 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3717 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003718
Anders Carlssondca83c42009-03-28 06:23:46 +00003719 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003720 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003721 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003722 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003723 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003724 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003725 if (!R.isAmbiguous() && !R.empty() &&
3726 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003727 return DeclPtrTy();
3728 }
Mike Stump11289f42009-09-09 15:08:12 +00003729
Anders Carlssondca83c42009-03-28 06:23:46 +00003730 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3731 diag::err_redefinition_different_kind;
3732 Diag(AliasLoc, DiagID) << Alias;
3733 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003734 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003735 }
3736
John McCall27b18f82009-11-17 02:14:36 +00003737 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003738 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003739
John McCall9f3059a2009-10-09 21:13:30 +00003740 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003741 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003742 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003745 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003746 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3747 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003748 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003749 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003750
John McCalld8d0d432010-02-16 06:53:13 +00003751 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003752 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003753}
3754
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003755void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3756 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003757 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3758 !Constructor->isUsed()) &&
3759 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003760
Eli Friedman9cf6b592009-11-09 19:20:36 +00003761 CXXRecordDecl *ClassDecl
3762 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3763 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003764
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003765 DeclContext *PreviousContext = CurContext;
3766 CurContext = Constructor;
3767 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003768 Diag(CurrentLocation, diag::note_member_synthesized_at)
3769 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003770 Constructor->setInvalidDecl();
3771 } else {
3772 Constructor->setUsed();
3773 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003774 CurContext = PreviousContext;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003775}
3776
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003777void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003778 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003779 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3780 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003781 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003782 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003783
3784 DeclContext *PreviousContext = CurContext;
3785 CurContext = Destructor;
3786
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003787 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003788 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003789 // implicitly defined, all the implicitly-declared default destructors
3790 // for its base class and its non-static data members shall have been
3791 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3793 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003794 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003796 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003797 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003798 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3799 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3800 else
Mike Stump11289f42009-09-09 15:08:12 +00003801 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003802 "DefineImplicitDestructor - missing dtor in a base class");
3803 }
3804 }
Mike Stump11289f42009-09-09 15:08:12 +00003805
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003806 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3807 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003808 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3809 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3810 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003811 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003812 CXXRecordDecl *FieldClassDecl
3813 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3814 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003815 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003816 const_cast<CXXDestructorDecl*>(
3817 FieldClassDecl->getDestructor(Context)))
3818 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3819 else
Mike Stump11289f42009-09-09 15:08:12 +00003820 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003821 "DefineImplicitDestructor - missing dtor in class of a data member");
3822 }
3823 }
3824 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003825
3826 // FIXME: If CheckDestructor fails, we should emit a note about where the
3827 // implicit destructor was needed.
3828 if (CheckDestructor(Destructor)) {
3829 Diag(CurrentLocation, diag::note_member_synthesized_at)
3830 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3831
3832 Destructor->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003833 CurContext = PreviousContext;
3834
Anders Carlsson26a807d2009-11-30 21:24:50 +00003835 return;
3836 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003837 CurContext = PreviousContext;
Anders Carlsson26a807d2009-11-30 21:24:50 +00003838
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003839 Destructor->setUsed();
3840}
3841
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003842void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3843 CXXMethodDecl *MethodDecl) {
3844 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3845 MethodDecl->getOverloadedOperator() == OO_Equal &&
3846 !MethodDecl->isUsed()) &&
3847 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003848
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003849 CXXRecordDecl *ClassDecl
3850 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003851
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003852 DeclContext *PreviousContext = CurContext;
3853 CurContext = MethodDecl;
3854
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003855 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003856 // Before the implicitly-declared copy assignment operator for a class is
3857 // implicitly defined, all implicitly-declared copy assignment operators
3858 // for its direct base classes and its nonstatic data members shall have
3859 // been implicitly defined.
3860 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003861 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3862 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003863 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003864 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003865 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003866 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3867 BaseClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003868 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3869 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003870 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3871 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003872 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3873 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3874 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003875 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003876 CXXRecordDecl *FieldClassDecl
3877 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003878 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003879 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3880 FieldClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003881 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003882 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003883 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003884 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3885 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003886 Diag(CurrentLocation, diag::note_first_required_here);
3887 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003888 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003889 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003890 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3891 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003892 Diag(CurrentLocation, diag::note_first_required_here);
3893 err = true;
3894 }
3895 }
3896 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003897 MethodDecl->setUsed();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003898
3899 CurContext = PreviousContext;
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003900}
3901
3902CXXMethodDecl *
Anders Carlssonefa47322009-12-09 03:01:51 +00003903Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3904 ParmVarDecl *ParmDecl,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003905 CXXRecordDecl *ClassDecl) {
3906 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3907 QualType RHSType(LHSType);
3908 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003909 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003910 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003911 RHSType = Context.getCVRQualifiedType(RHSType,
3912 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003913 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003914 LHSType,
3915 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003916 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003917 RHSType,
3918 CurrentLocation));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003919 Expr *Args[2] = { &*LHS, &*RHS };
John McCallbc077cf2010-02-08 23:07:23 +00003920 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump11289f42009-09-09 15:08:12 +00003921 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003922 CandidateSet);
3923 OverloadCandidateSet::iterator Best;
Anders Carlssonefa47322009-12-09 03:01:51 +00003924 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003925 return cast<CXXMethodDecl>(Best->Function);
3926 assert(false &&
3927 "getAssignOperatorMethod - copy assignment operator method not found");
3928 return 0;
3929}
3930
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003931void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3932 CXXConstructorDecl *CopyConstructor,
3933 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003934 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00003935 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003936 !CopyConstructor->isUsed()) &&
3937 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003938
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003939 CXXRecordDecl *ClassDecl
3940 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3941 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003942
3943 DeclContext *PreviousContext = CurContext;
3944 CurContext = CopyConstructor;
3945
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003946 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003947 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003948 // implicitly defined, all the implicitly-declared copy constructors
3949 // for its base class and its non-static data members shall have been
3950 // implicitly defined.
3951 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3952 Base != ClassDecl->bases_end(); ++Base) {
3953 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003954 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003955 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003956 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003957 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003958 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003959 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3960 FieldEnd = ClassDecl->field_end();
3961 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003962 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3963 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3964 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003965 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003966 CXXRecordDecl *FieldClassDecl
3967 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003968 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003969 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003970 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003971 }
3972 }
3973 CopyConstructor->setUsed();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003974
3975 CurContext = PreviousContext;
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003976}
3977
Anders Carlsson6eb55572009-08-25 05:12:04 +00003978Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003979Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003980 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003981 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003982 bool RequiresZeroInit,
3983 bool BaseInitialization) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003984 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003986 // C++ [class.copy]p15:
3987 // Whenever a temporary class object is copied using a copy constructor, and
3988 // this object and the copy have the same cv-unqualified type, an
3989 // implementation is permitted to treat the original and the copy as two
3990 // different ways of referring to the same object and not perform a copy at
3991 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003992
Anders Carlsson250aada2009-08-16 05:13:48 +00003993 // FIXME: Is this enough?
Douglas Gregor507eb872009-12-22 00:34:07 +00003994 if (Constructor->isCopyConstructor()) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003995 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregore1314a62009-12-18 05:02:21 +00003996 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3997 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3998 E = ICE->getSubExpr();
Eli Friedmanfddc26c2009-12-24 23:33:34 +00003999 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
4000 E = FCE->getSubExpr();
Anders Carlsson250aada2009-08-16 05:13:48 +00004001 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
4002 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004003 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4004 if (ICE->getCastKind() == CastExpr::CK_NoOp)
4005 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00004006
4007 if (CallExpr *CE = dyn_cast<CallExpr>(E))
4008 Elidable = !CE->getCallReturnType()->isReferenceType();
4009 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00004010 Elidable = true;
Eli Friedmanfddc26c2009-12-24 23:33:34 +00004011 else if (isa<CXXConstructExpr>(E))
4012 Elidable = true;
Anders Carlsson250aada2009-08-16 05:13:48 +00004013 }
Mike Stump11289f42009-09-09 15:08:12 +00004014
4015 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004016 Elidable, move(ExprArgs), RequiresZeroInit,
4017 BaseInitialization);
Anders Carlsson250aada2009-08-16 05:13:48 +00004018}
4019
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004020/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4021/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004022Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004023Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4024 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004025 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004026 bool RequiresZeroInit,
4027 bool BaseInitialization) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004028 unsigned NumExprs = ExprArgs.size();
4029 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004030
Douglas Gregor27381f32009-11-23 12:27:39 +00004031 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004032 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004033 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004034 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004035}
4036
Mike Stump11289f42009-09-09 15:08:12 +00004037bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004038 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004039 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004040 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004041 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004042 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004043 if (TempResult.isInvalid())
4044 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004045
Anders Carlsson6eb55572009-08-25 05:12:04 +00004046 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004047 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004048 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004049 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004050
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004051 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004052}
4053
John McCall03c48482010-02-02 09:10:11 +00004054void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4055 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004056 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4057 !ClassDecl->hasTrivialDestructor()) {
John McCall6781b052010-02-02 08:45:54 +00004058 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4059 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall03c48482010-02-02 09:10:11 +00004060 CheckDestructorAccess(VD->getLocation(), Record);
John McCall6781b052010-02-02 08:45:54 +00004061 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004062}
4063
Mike Stump11289f42009-09-09 15:08:12 +00004064/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004065/// ActOnDeclarator, when a C++ direct initializer is present.
4066/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004067void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4068 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004069 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004070 SourceLocation *CommaLocs,
4071 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004072 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004073 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004074
4075 // If there is no declaration, there was an error parsing it. Just ignore
4076 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004077 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004078 return;
Mike Stump11289f42009-09-09 15:08:12 +00004079
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004080 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4081 if (!VDecl) {
4082 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4083 RealDecl->setInvalidDecl();
4084 return;
4085 }
4086
Douglas Gregor402250f2009-08-26 21:14:46 +00004087 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004088 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004089 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4090 //
4091 // Clients that want to distinguish between the two forms, can check for
4092 // direct initializer using VarDecl::hasCXXDirectInitializer().
4093 // A major benefit is that clients that don't particularly care about which
4094 // exactly form was it (like the CodeGen) can handle both cases without
4095 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004096
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004097 // C++ 8.5p11:
4098 // The form of initialization (using parentheses or '=') is generally
4099 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004100 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004101 QualType DeclInitType = VDecl->getType();
4102 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004103 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004104
Douglas Gregor50dc2192010-02-11 22:55:30 +00004105 if (!VDecl->getType()->isDependentType() &&
4106 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004107 diag::err_typecheck_decl_incomplete_type)) {
4108 VDecl->setInvalidDecl();
4109 return;
4110 }
4111
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004112 // The variable can not have an abstract class type.
4113 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4114 diag::err_abstract_type_in_decl,
4115 AbstractVariableType))
4116 VDecl->setInvalidDecl();
4117
Sebastian Redl5ca79842010-02-01 20:16:42 +00004118 const VarDecl *Def;
4119 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004120 Diag(VDecl->getLocation(), diag::err_redefinition)
4121 << VDecl->getDeclName();
4122 Diag(Def->getLocation(), diag::note_previous_definition);
4123 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004124 return;
4125 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004126
4127 // If either the declaration has a dependent type or if any of the
4128 // expressions is type-dependent, we represent the initialization
4129 // via a ParenListExpr for later use during template instantiation.
4130 if (VDecl->getType()->isDependentType() ||
4131 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4132 // Let clients know that initialization was done with a direct initializer.
4133 VDecl->setCXXDirectInitializer(true);
4134
4135 // Store the initialization expressions as a ParenListExpr.
4136 unsigned NumExprs = Exprs.size();
4137 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4138 (Expr **)Exprs.release(),
4139 NumExprs, RParenLoc));
4140 return;
4141 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004142
4143 // Capture the variable that is being initialized and the style of
4144 // initialization.
4145 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4146
4147 // FIXME: Poor source location information.
4148 InitializationKind Kind
4149 = InitializationKind::CreateDirect(VDecl->getLocation(),
4150 LParenLoc, RParenLoc);
4151
4152 InitializationSequence InitSeq(*this, Entity, Kind,
4153 (Expr**)Exprs.get(), Exprs.size());
4154 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4155 if (Result.isInvalid()) {
4156 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004157 return;
4158 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004159
4160 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004161 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004162 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004163
John McCall03c48482010-02-02 09:10:11 +00004164 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4165 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004166}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004167
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004168/// \brief Add the applicable constructor candidates for an initialization
4169/// by constructor.
4170static void AddConstructorInitializationCandidates(Sema &SemaRef,
4171 QualType ClassType,
4172 Expr **Args,
4173 unsigned NumArgs,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004174 InitializationKind Kind,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004175 OverloadCandidateSet &CandidateSet) {
4176 // C++ [dcl.init]p14:
4177 // If the initialization is direct-initialization, or if it is
4178 // copy-initialization where the cv-unqualified version of the
4179 // source type is the same class as, or a derived class of, the
4180 // class of the destination, constructors are considered. The
4181 // applicable constructors are enumerated (13.3.1.3), and the
4182 // best one is chosen through overload resolution (13.3). The
4183 // constructor so selected is called to initialize the object,
4184 // with the initializer expression(s) as its argument(s). If no
4185 // constructor applies, or the overload resolution is ambiguous,
4186 // the initialization is ill-formed.
4187 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4188 assert(ClassRec && "Can only initialize a class type here");
4189
4190 // FIXME: When we decide not to synthesize the implicitly-declared
4191 // constructors, we'll need to make them appear here.
4192
4193 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4194 DeclarationName ConstructorName
4195 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4196 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4197 DeclContext::lookup_const_iterator Con, ConEnd;
4198 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4199 Con != ConEnd; ++Con) {
4200 // Find the constructor (which may be a template).
4201 CXXConstructorDecl *Constructor = 0;
4202 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4203 if (ConstructorTmpl)
4204 Constructor
4205 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4206 else
4207 Constructor = cast<CXXConstructorDecl>(*Con);
4208
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004209 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4210 (Kind.getKind() == InitializationKind::IK_Value) ||
4211 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004212 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004213 ((Kind.getKind() == InitializationKind::IK_Default) &&
4214 Constructor->isDefaultConstructor())) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004215 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00004216 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCallb89836b2010-01-26 01:37:31 +00004217 ConstructorTmpl->getAccess(),
John McCall6b51f282009-11-23 01:53:49 +00004218 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004219 Args, NumArgs, CandidateSet);
4220 else
John McCallb89836b2010-01-26 01:37:31 +00004221 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4222 Args, NumArgs, CandidateSet);
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004223 }
4224 }
4225}
4226
4227/// \brief Attempt to perform initialization by constructor
4228/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4229/// copy-initialization.
4230///
4231/// This routine determines whether initialization by constructor is possible,
4232/// but it does not emit any diagnostics in the case where the initialization
4233/// is ill-formed.
4234///
4235/// \param ClassType the type of the object being initialized, which must have
4236/// class type.
4237///
4238/// \param Args the arguments provided to initialize the object
4239///
4240/// \param NumArgs the number of arguments provided to initialize the object
4241///
4242/// \param Kind the type of initialization being performed
4243///
4244/// \returns the constructor used to initialize the object, if successful.
4245/// Otherwise, emits a diagnostic and returns NULL.
4246CXXConstructorDecl *
4247Sema::TryInitializationByConstructor(QualType ClassType,
4248 Expr **Args, unsigned NumArgs,
4249 SourceLocation Loc,
4250 InitializationKind Kind) {
4251 // Build the overload candidate set
John McCallbc077cf2010-02-08 23:07:23 +00004252 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004253 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4254 CandidateSet);
4255
4256 // Determine whether we found a constructor we can use.
4257 OverloadCandidateSet::iterator Best;
4258 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4259 case OR_Success:
4260 case OR_Deleted:
4261 // We found a constructor. Return it.
4262 return cast<CXXConstructorDecl>(Best->Function);
4263
4264 case OR_No_Viable_Function:
4265 case OR_Ambiguous:
4266 // Overload resolution failed. Return nothing.
4267 return 0;
4268 }
4269
4270 // Silence GCC warning
4271 return 0;
4272}
4273
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004274/// \brief Given a constructor and the set of arguments provided for the
4275/// constructor, convert the arguments and add any required default arguments
4276/// to form a proper call to this constructor.
4277///
4278/// \returns true if an error occurred, false otherwise.
4279bool
4280Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4281 MultiExprArg ArgsPtr,
4282 SourceLocation Loc,
4283 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4284 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4285 unsigned NumArgs = ArgsPtr.size();
4286 Expr **Args = (Expr **)ArgsPtr.get();
4287
4288 const FunctionProtoType *Proto
4289 = Constructor->getType()->getAs<FunctionProtoType>();
4290 assert(Proto && "Constructor without a prototype?");
4291 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004292
4293 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004294 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004295 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004296 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004297 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004298
4299 VariadicCallType CallType =
4300 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4301 llvm::SmallVector<Expr *, 8> AllArgs;
4302 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4303 Proto, 0, Args, NumArgs, AllArgs,
4304 CallType);
4305 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4306 ConvertedArgs.push_back(AllArgs[i]);
4307 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004308}
4309
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004310/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4311/// determine whether they are reference-related,
4312/// reference-compatible, reference-compatible with added
4313/// qualification, or incompatible, for use in C++ initialization by
4314/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4315/// type, and the first type (T1) is the pointee type of the reference
4316/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00004317Sema::ReferenceCompareResult
Chandler Carruth607f38e2009-12-29 07:16:59 +00004318Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004319 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00004320 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004321 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004322 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004323 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004324
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004325 QualType T1 = Context.getCanonicalType(OrigT1);
4326 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004327 Qualifiers T1Quals, T2Quals;
4328 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4329 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004330
4331 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004332 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00004333 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004334 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00004335 if (UnqualT1 == UnqualT2)
4336 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004337 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4338 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4339 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00004340 DerivedToBase = true;
4341 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004342 return Ref_Incompatible;
4343
4344 // At this point, we know that T1 and T2 are reference-related (at
4345 // least).
4346
Chandler Carruth607f38e2009-12-29 07:16:59 +00004347 // If the type is an array type, promote the element qualifiers to the type
4348 // for comparison.
4349 if (isa<ArrayType>(T1) && T1Quals)
4350 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4351 if (isa<ArrayType>(T2) && T2Quals)
4352 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4353
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004354 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004355 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004356 // reference-related to T2 and cv1 is the same cv-qualification
4357 // as, or greater cv-qualification than, cv2. For purposes of
4358 // overload resolution, cases for which cv1 is greater
4359 // cv-qualification than cv2 are identified as
4360 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth607f38e2009-12-29 07:16:59 +00004361 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004362 return Ref_Compatible;
4363 else if (T1.isMoreQualifiedThan(T2))
4364 return Ref_Compatible_With_Added_Qualification;
4365 else
4366 return Ref_Related;
4367}
4368
4369/// CheckReferenceInit - Check the initialization of a reference
4370/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4371/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00004372/// list), and DeclType is the type of the declaration. When ICS is
4373/// non-null, this routine will compute the implicit conversion
4374/// sequence according to C++ [over.ics.ref] and will not produce any
4375/// diagnostics; when ICS is null, it will emit diagnostics when any
4376/// errors are found. Either way, a return value of true indicates
4377/// that there was a failure, a return value of false indicates that
4378/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00004379///
4380/// When @p SuppressUserConversions, user-defined conversions are
4381/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004382/// When @p AllowExplicit, we also permit explicit user-defined
4383/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00004384/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00004385/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4386/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00004387bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00004388Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00004389 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004390 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00004391 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00004392 ImplicitConversionSequence *ICS,
4393 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004394 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4395
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004396 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004397 QualType T2 = Init->getType();
4398
Douglas Gregorcd695e52008-11-10 20:40:00 +00004399 // If the initializer is the address of an overloaded function, try
4400 // to resolve the overloaded function. If all goes well, T2 is the
4401 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004402 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00004403 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004404 ICS != 0);
4405 if (Fn) {
4406 // Since we're performing this reference-initialization for
4407 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004408 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00004409 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004410 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004411
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00004412 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004413 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004414
4415 T2 = Fn->getType();
4416 }
4417 }
4418
Douglas Gregor786ab212008-10-29 02:00:59 +00004419 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004420 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00004421 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00004422 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4423 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00004424 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004425 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00004426
4427 // Most paths end in a failed conversion.
John McCall6a61b522010-01-13 09:16:55 +00004428 if (ICS) {
John McCall65eb8792010-02-25 01:37:24 +00004429 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCall6a61b522010-01-13 09:16:55 +00004430 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004431
4432 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004433 // A reference to type "cv1 T1" is initialized by an expression
4434 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004435
4436 // -- If the initializer expression
4437
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004438 // Rvalue references cannot bind to lvalues (N2812).
4439 // There is absolutely no situation where they can. In particular, note that
4440 // this is ill-formed, even if B has a user-defined conversion to A&&:
4441 // B b;
4442 // A&& r = b;
4443 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4444 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004445 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004446 << Init->getSourceRange();
4447 return true;
4448 }
4449
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004450 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00004451 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4452 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00004453 //
4454 // Note that the bit-field check is skipped if we are just computing
4455 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00004456 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004457 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004458 BindsDirectly = true;
4459
Douglas Gregor786ab212008-10-29 02:00:59 +00004460 if (ICS) {
4461 // C++ [over.ics.ref]p1:
4462 // When a parameter of reference type binds directly (8.5.3)
4463 // to an argument expression, the implicit conversion sequence
4464 // is the identity conversion, unless the argument expression
4465 // has a type that is a derived class of the parameter type,
4466 // in which case the implicit conversion sequence is a
4467 // derived-to-base Conversion (13.3.3.1).
John McCall0d1da222010-01-12 00:44:57 +00004468 ICS->setStandard();
Douglas Gregor786ab212008-10-29 02:00:59 +00004469 ICS->Standard.First = ICK_Identity;
4470 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4471 ICS->Standard.Third = ICK_Identity;
4472 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004473 ICS->Standard.setToType(0, T2);
4474 ICS->Standard.setToType(1, T1);
4475 ICS->Standard.setToType(2, T1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004476 ICS->Standard.ReferenceBinding = true;
4477 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004478 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004479 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004480
4481 // Nothing more to do: the inaccessibility/ambiguity check for
4482 // derived-to-base conversions is suppressed when we're
4483 // computing the implicit conversion sequence (C++
4484 // [over.best.ics]p2).
4485 return false;
4486 } else {
4487 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004488 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4489 if (DerivedToBase)
4490 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004491 else if(CheckExceptionSpecCompatibility(Init, T1))
4492 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004493 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004494 }
4495 }
4496
4497 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00004498 // implicitly converted to an lvalue of type "cv3 T3,"
4499 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004500 // 92) (this conversion is selected by enumerating the
4501 // applicable conversion functions (13.3.1.6) and choosing
4502 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004503 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004504 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00004505 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004506 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004507
John McCallbc077cf2010-02-08 23:07:23 +00004508 OverloadCandidateSet CandidateSet(DeclLoc);
John McCallad371252010-01-20 00:46:10 +00004509 const UnresolvedSetImpl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004510 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004511 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004512 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00004513 NamedDecl *D = *I;
4514 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4515 if (isa<UsingShadowDecl>(D))
4516 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4517
Mike Stump11289f42009-09-09 15:08:12 +00004518 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00004519 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00004520 CXXConversionDecl *Conv;
4521 if (ConvTemplate)
4522 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4523 else
John McCall6e9f8f62009-12-03 04:06:58 +00004524 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004525
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004526 // If the conversion function doesn't return a reference type,
4527 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004528 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00004529 (AllowExplicit || !Conv->isExplicit())) {
4530 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00004531 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall6e9f8f62009-12-03 04:06:58 +00004532 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004533 else
John McCallb89836b2010-01-26 01:37:31 +00004534 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4535 DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004536 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004537 }
4538
4539 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00004540 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004541 case OR_Success:
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004542 // C++ [over.ics.ref]p1:
4543 //
4544 // [...] If the parameter binds directly to the result of
4545 // applying a conversion function to the argument
4546 // expression, the implicit conversion sequence is a
4547 // user-defined conversion sequence (13.3.3.1.2), with the
4548 // second standard conversion sequence either an identity
4549 // conversion or, if the conversion function returns an
4550 // entity of a type that is a derived class of the parameter
4551 // type, a derived-to-base Conversion.
4552 if (!Best->FinalConversion.DirectBinding)
4553 break;
4554
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004555 // This is a direct binding.
4556 BindsDirectly = true;
4557
4558 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004559 ICS->setUserDefined();
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004560 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4561 ICS->UserDefined.After = Best->FinalConversion;
4562 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004563 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004564 assert(ICS->UserDefined.After.ReferenceBinding &&
4565 ICS->UserDefined.After.DirectBinding &&
4566 "Expected a direct reference binding!");
4567 return false;
4568 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004569 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004570 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004571 CastExpr::CK_UserDefinedConversion,
4572 cast<CXXMethodDecl>(Best->Function),
4573 Owned(Init));
4574 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004575
4576 if (CheckExceptionSpecCompatibility(Init, T1))
4577 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004578 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4579 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004580 }
4581 break;
4582
4583 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004584 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004585 ICS->setAmbiguous();
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004586 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4587 Cand != CandidateSet.end(); ++Cand)
4588 if (Cand->Viable)
John McCall0d1da222010-01-12 00:44:57 +00004589 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004590 break;
4591 }
4592 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4593 << Init->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00004594 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004595 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004596
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004597 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004598 case OR_Deleted:
4599 // There was no suitable conversion, or we found a deleted
4600 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004601 break;
4602 }
4603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004605 if (BindsDirectly) {
4606 // C++ [dcl.init.ref]p4:
4607 // [...] In all cases where the reference-related or
4608 // reference-compatible relationship of two types is used to
4609 // establish the validity of a reference binding, and T1 is a
4610 // base class of T2, a program that necessitates such a binding
4611 // is ill-formed if T1 is an inaccessible (clause 11) or
4612 // ambiguous (10.2) base class of T2.
4613 //
4614 // Note that we only check this condition when we're allowed to
4615 // complain about errors, because we should not be checking for
4616 // ambiguity (or inaccessibility) unless the reference binding
4617 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004618 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004619 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004620 Init->getSourceRange(),
4621 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004622 else
4623 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004624 }
4625
4626 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004627 // type (i.e., cv1 shall be const), or the reference shall be an
4628 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004629 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004630 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004631 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregord1e08642010-01-29 19:39:15 +00004632 << T1.isVolatileQualified()
Douglas Gregor906db8a2009-12-15 16:44:32 +00004633 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004634 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004635 return true;
4636 }
4637
4638 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004639 // class type, and "cv1 T1" is reference-compatible with
4640 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004641 // following ways (the choice is implementation-defined):
4642 //
4643 // -- The reference is bound to the object represented by
4644 // the rvalue (see 3.10) or to a sub-object within that
4645 // object.
4646 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004647 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004648 // a constructor is called to copy the entire rvalue
4649 // object into the temporary. The reference is bound to
4650 // the temporary or to a sub-object within the
4651 // temporary.
4652 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004653 // The constructor that would be used to make the copy
4654 // shall be callable whether or not the copy is actually
4655 // done.
4656 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004657 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004658 // freedom, so we will always take the first option and never build
4659 // a temporary in this case. FIXME: We will, however, have to check
4660 // for the presence of a copy constructor in C++98/03 mode.
4661 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004662 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4663 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004664 ICS->setStandard();
Douglas Gregor786ab212008-10-29 02:00:59 +00004665 ICS->Standard.First = ICK_Identity;
4666 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4667 ICS->Standard.Third = ICK_Identity;
4668 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004669 ICS->Standard.setToType(0, T2);
4670 ICS->Standard.setToType(1, T1);
4671 ICS->Standard.setToType(2, T1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004672 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004673 ICS->Standard.DirectBinding = false;
4674 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004675 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004676 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004677 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4678 if (DerivedToBase)
4679 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004680 else if(CheckExceptionSpecCompatibility(Init, T1))
4681 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004682 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004683 }
4684 return false;
4685 }
4686
Eli Friedman44b83ee2009-08-05 19:21:58 +00004687 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004688 // initialized from the initializer expression using the
4689 // rules for a non-reference copy initialization (8.5). The
4690 // reference is then bound to the temporary. If T1 is
4691 // reference-related to T2, cv1 must be the same
4692 // cv-qualification as, or greater cv-qualification than,
4693 // cv2; otherwise, the program is ill-formed.
4694 if (RefRelationship == Ref_Related) {
4695 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4696 // we would be reference-compatible or reference-compatible with
4697 // added qualification. But that wasn't the case, so the reference
4698 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004699 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004700 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor906db8a2009-12-15 16:44:32 +00004701 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004702 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004703 return true;
4704 }
4705
Douglas Gregor576e98c2009-01-30 23:27:23 +00004706 // If at least one of the types is a class type, the types are not
4707 // related, and we aren't allowed any user conversions, the
4708 // reference binding fails. This case is important for breaking
4709 // recursion, since TryImplicitConversion below will attempt to
4710 // create a temporary through the use of a copy constructor.
4711 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4712 (T1->isRecordType() || T2->isRecordType())) {
4713 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004714 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004715 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor576e98c2009-01-30 23:27:23 +00004716 return true;
4717 }
4718
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004719 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004720 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004721 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004722 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004723 // When a parameter of reference type is not bound directly to
4724 // an argument expression, the conversion sequence is the one
4725 // required to convert the argument expression to the
4726 // underlying type of the reference according to
4727 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4728 // to copy-initializing a temporary of the underlying type with
4729 // the argument expression. Any difference in top-level
4730 // cv-qualification is subsumed by the initialization itself
4731 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004732 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4733 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004734 /*ForceRValue=*/false,
4735 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004736
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004737 // Of course, that's still a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004738 if (ICS->isStandard()) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004739 ICS->Standard.ReferenceBinding = true;
4740 ICS->Standard.RRefBinding = isRValRef;
John McCall0d1da222010-01-12 00:44:57 +00004741 } else if (ICS->isUserDefined()) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004742 ICS->UserDefined.After.ReferenceBinding = true;
4743 ICS->UserDefined.After.RRefBinding = isRValRef;
4744 }
John McCall0d1da222010-01-12 00:44:57 +00004745 return ICS->isBad();
Douglas Gregor786ab212008-10-29 02:00:59 +00004746 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004747 ImplicitConversionSequence Conversions;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004748 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004749 false, false,
4750 Conversions);
4751 if (badConversion) {
John McCall0d1da222010-01-12 00:44:57 +00004752 if (Conversions.isAmbiguous()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004753 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004754 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall0d1da222010-01-12 00:44:57 +00004755 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004756 j >= 0; j--) {
John McCall0d1da222010-01-12 00:44:57 +00004757 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallfd0b2f82010-01-06 09:43:14 +00004758 NoteOverloadCandidate(Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004759 }
4760 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004761 else {
4762 if (isRValRef)
4763 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4764 << Init->getSourceRange();
4765 else
4766 Diag(DeclLoc, diag::err_invalid_initialization)
4767 << DeclType << Init->getType() << Init->getSourceRange();
4768 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004769 }
4770 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004771 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004772}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004773
Anders Carlssone363c8e2009-12-12 00:32:00 +00004774static inline bool
4775CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4776 const FunctionDecl *FnDecl) {
4777 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4778 if (isa<NamespaceDecl>(DC)) {
4779 return SemaRef.Diag(FnDecl->getLocation(),
4780 diag::err_operator_new_delete_declared_in_namespace)
4781 << FnDecl->getDeclName();
4782 }
4783
4784 if (isa<TranslationUnitDecl>(DC) &&
4785 FnDecl->getStorageClass() == FunctionDecl::Static) {
4786 return SemaRef.Diag(FnDecl->getLocation(),
4787 diag::err_operator_new_delete_declared_static)
4788 << FnDecl->getDeclName();
4789 }
4790
Anders Carlsson60659a82009-12-12 02:43:16 +00004791 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004792}
4793
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004794static inline bool
4795CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4796 CanQualType ExpectedResultType,
4797 CanQualType ExpectedFirstParamType,
4798 unsigned DependentParamTypeDiag,
4799 unsigned InvalidParamTypeDiag) {
4800 QualType ResultType =
4801 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4802
4803 // Check that the result type is not dependent.
4804 if (ResultType->isDependentType())
4805 return SemaRef.Diag(FnDecl->getLocation(),
4806 diag::err_operator_new_delete_dependent_result_type)
4807 << FnDecl->getDeclName() << ExpectedResultType;
4808
4809 // Check that the result type is what we expect.
4810 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4811 return SemaRef.Diag(FnDecl->getLocation(),
4812 diag::err_operator_new_delete_invalid_result_type)
4813 << FnDecl->getDeclName() << ExpectedResultType;
4814
4815 // A function template must have at least 2 parameters.
4816 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4817 return SemaRef.Diag(FnDecl->getLocation(),
4818 diag::err_operator_new_delete_template_too_few_parameters)
4819 << FnDecl->getDeclName();
4820
4821 // The function decl must have at least 1 parameter.
4822 if (FnDecl->getNumParams() == 0)
4823 return SemaRef.Diag(FnDecl->getLocation(),
4824 diag::err_operator_new_delete_too_few_parameters)
4825 << FnDecl->getDeclName();
4826
4827 // Check the the first parameter type is not dependent.
4828 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4829 if (FirstParamType->isDependentType())
4830 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4831 << FnDecl->getDeclName() << ExpectedFirstParamType;
4832
4833 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004834 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004835 ExpectedFirstParamType)
4836 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4837 << FnDecl->getDeclName() << ExpectedFirstParamType;
4838
4839 return false;
4840}
4841
Anders Carlsson12308f42009-12-11 23:23:22 +00004842static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004843CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004844 // C++ [basic.stc.dynamic.allocation]p1:
4845 // A program is ill-formed if an allocation function is declared in a
4846 // namespace scope other than global scope or declared static in global
4847 // scope.
4848 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4849 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004850
4851 CanQualType SizeTy =
4852 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4853
4854 // C++ [basic.stc.dynamic.allocation]p1:
4855 // The return type shall be void*. The first parameter shall have type
4856 // std::size_t.
4857 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4858 SizeTy,
4859 diag::err_operator_new_dependent_param_type,
4860 diag::err_operator_new_param_type))
4861 return true;
4862
4863 // C++ [basic.stc.dynamic.allocation]p1:
4864 // The first parameter shall not have an associated default argument.
4865 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004866 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004867 diag::err_operator_new_default_arg)
4868 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4869
4870 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004871}
4872
4873static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004874CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4875 // C++ [basic.stc.dynamic.deallocation]p1:
4876 // A program is ill-formed if deallocation functions are declared in a
4877 // namespace scope other than global scope or declared static in global
4878 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004879 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4880 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004881
4882 // C++ [basic.stc.dynamic.deallocation]p2:
4883 // Each deallocation function shall return void and its first parameter
4884 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004885 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4886 SemaRef.Context.VoidPtrTy,
4887 diag::err_operator_delete_dependent_param_type,
4888 diag::err_operator_delete_param_type))
4889 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004890
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004891 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4892 if (FirstParamType->isDependentType())
4893 return SemaRef.Diag(FnDecl->getLocation(),
4894 diag::err_operator_delete_dependent_param_type)
4895 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4896
4897 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4898 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00004899 return SemaRef.Diag(FnDecl->getLocation(),
4900 diag::err_operator_delete_param_type)
4901 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00004902
4903 return false;
4904}
4905
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004906/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4907/// of this overloaded operator is well-formed. If so, returns false;
4908/// otherwise, emits appropriate diagnostics and returns true.
4909bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004910 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004911 "Expected an overloaded operator declaration");
4912
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004913 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4914
Mike Stump11289f42009-09-09 15:08:12 +00004915 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004916 // The allocation and deallocation functions, operator new,
4917 // operator new[], operator delete and operator delete[], are
4918 // described completely in 3.7.3. The attributes and restrictions
4919 // found in the rest of this subclause do not apply to them unless
4920 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00004921 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00004922 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004923
Anders Carlsson22f443f2009-12-12 00:26:23 +00004924 if (Op == OO_New || Op == OO_Array_New)
4925 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004926
4927 // C++ [over.oper]p6:
4928 // An operator function shall either be a non-static member
4929 // function or be a non-member function and have at least one
4930 // parameter whose type is a class, a reference to a class, an
4931 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004932 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4933 if (MethodDecl->isStatic())
4934 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004935 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004936 } else {
4937 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004938 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4939 ParamEnd = FnDecl->param_end();
4940 Param != ParamEnd; ++Param) {
4941 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004942 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4943 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004944 ClassOrEnumParam = true;
4945 break;
4946 }
4947 }
4948
Douglas Gregord69246b2008-11-17 16:14:12 +00004949 if (!ClassOrEnumParam)
4950 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004951 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004952 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004953 }
4954
4955 // C++ [over.oper]p8:
4956 // An operator function cannot have default arguments (8.3.6),
4957 // except where explicitly stated below.
4958 //
Mike Stump11289f42009-09-09 15:08:12 +00004959 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004960 // (C++ [over.call]p1).
4961 if (Op != OO_Call) {
4962 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4963 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004964 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004965 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004966 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004967 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004968 }
4969 }
4970
Douglas Gregor6cf08062008-11-10 13:38:07 +00004971 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4972 { false, false, false }
4973#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4974 , { Unary, Binary, MemberOnly }
4975#include "clang/Basic/OperatorKinds.def"
4976 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004977
Douglas Gregor6cf08062008-11-10 13:38:07 +00004978 bool CanBeUnaryOperator = OperatorUses[Op][0];
4979 bool CanBeBinaryOperator = OperatorUses[Op][1];
4980 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004981
4982 // C++ [over.oper]p8:
4983 // [...] Operator functions cannot have more or fewer parameters
4984 // than the number required for the corresponding operator, as
4985 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004986 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004987 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004988 if (Op != OO_Call &&
4989 ((NumParams == 1 && !CanBeUnaryOperator) ||
4990 (NumParams == 2 && !CanBeBinaryOperator) ||
4991 (NumParams < 1) || (NumParams > 2))) {
4992 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004993 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004994 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004995 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004996 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004997 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004998 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004999 assert(CanBeBinaryOperator &&
5000 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005001 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005002 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005003
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005004 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005005 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005006 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005007
Douglas Gregord69246b2008-11-17 16:14:12 +00005008 // Overloaded operators other than operator() cannot be variadic.
5009 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005010 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005011 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005012 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005013 }
5014
5015 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005016 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5017 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005018 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005019 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005020 }
5021
5022 // C++ [over.inc]p1:
5023 // The user-defined function called operator++ implements the
5024 // prefix and postfix ++ operator. If this function is a member
5025 // function with no parameters, or a non-member function with one
5026 // parameter of class or enumeration type, it defines the prefix
5027 // increment operator ++ for objects of that type. If the function
5028 // is a member function with one parameter (which shall be of type
5029 // int) or a non-member function with two parameters (the second
5030 // of which shall be of type int), it defines the postfix
5031 // increment operator ++ for objects of that type.
5032 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5033 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5034 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005035 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005036 ParamIsInt = BT->getKind() == BuiltinType::Int;
5037
Chris Lattner2b786902008-11-21 07:50:02 +00005038 if (!ParamIsInt)
5039 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005040 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005041 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005042 }
5043
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005044 // Notify the class if it got an assignment operator.
5045 if (Op == OO_Equal) {
5046 // Would have returned earlier otherwise.
5047 assert(isa<CXXMethodDecl>(FnDecl) &&
5048 "Overloaded = not member, but not filtered.");
5049 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5050 Method->getParent()->addedAssignmentOperator(Context, Method);
5051 }
5052
Douglas Gregord69246b2008-11-17 16:14:12 +00005053 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005054}
Chris Lattner3b024a32008-12-17 07:09:26 +00005055
Alexis Huntc88db062010-01-13 09:01:02 +00005056/// CheckLiteralOperatorDeclaration - Check whether the declaration
5057/// of this literal operator function is well-formed. If so, returns
5058/// false; otherwise, emits appropriate diagnostics and returns true.
5059bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5060 DeclContext *DC = FnDecl->getDeclContext();
5061 Decl::Kind Kind = DC->getDeclKind();
5062 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5063 Kind != Decl::LinkageSpec) {
5064 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5065 << FnDecl->getDeclName();
5066 return true;
5067 }
5068
5069 bool Valid = false;
5070
5071 // FIXME: Check for the one valid template signature
5072 // template <char...> type operator "" name();
5073
5074 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5075 // Check the first parameter
5076 QualType T = (*Param)->getType();
5077
5078 // unsigned long long int and long double are allowed, but only
5079 // alone.
5080 // We also allow any character type; their omission seems to be a bug
5081 // in n3000
5082 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5083 Context.hasSameType(T, Context.LongDoubleTy) ||
5084 Context.hasSameType(T, Context.CharTy) ||
5085 Context.hasSameType(T, Context.WCharTy) ||
5086 Context.hasSameType(T, Context.Char16Ty) ||
5087 Context.hasSameType(T, Context.Char32Ty)) {
5088 if (++Param == FnDecl->param_end())
5089 Valid = true;
5090 goto FinishedParams;
5091 }
5092
5093 // Otherwise it must be a pointer to const; let's strip those.
5094 const PointerType *PT = T->getAs<PointerType>();
5095 if (!PT)
5096 goto FinishedParams;
5097 T = PT->getPointeeType();
5098 if (!T.isConstQualified())
5099 goto FinishedParams;
5100 T = T.getUnqualifiedType();
5101
5102 // Move on to the second parameter;
5103 ++Param;
5104
5105 // If there is no second parameter, the first must be a const char *
5106 if (Param == FnDecl->param_end()) {
5107 if (Context.hasSameType(T, Context.CharTy))
5108 Valid = true;
5109 goto FinishedParams;
5110 }
5111
5112 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5113 // are allowed as the first parameter to a two-parameter function
5114 if (!(Context.hasSameType(T, Context.CharTy) ||
5115 Context.hasSameType(T, Context.WCharTy) ||
5116 Context.hasSameType(T, Context.Char16Ty) ||
5117 Context.hasSameType(T, Context.Char32Ty)))
5118 goto FinishedParams;
5119
5120 // The second and final parameter must be an std::size_t
5121 T = (*Param)->getType().getUnqualifiedType();
5122 if (Context.hasSameType(T, Context.getSizeType()) &&
5123 ++Param == FnDecl->param_end())
5124 Valid = true;
5125 }
5126
5127 // FIXME: This diagnostic is absolutely terrible.
5128FinishedParams:
5129 if (!Valid) {
5130 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5131 << FnDecl->getDeclName();
5132 return true;
5133 }
5134
5135 return false;
5136}
5137
Douglas Gregor07665a62009-01-05 19:45:36 +00005138/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5139/// linkage specification, including the language and (if present)
5140/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5141/// the location of the language string literal, which is provided
5142/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5143/// the '{' brace. Otherwise, this linkage specification does not
5144/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005145Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5146 SourceLocation ExternLoc,
5147 SourceLocation LangLoc,
5148 const char *Lang,
5149 unsigned StrSize,
5150 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005151 LinkageSpecDecl::LanguageIDs Language;
5152 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5153 Language = LinkageSpecDecl::lang_c;
5154 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5155 Language = LinkageSpecDecl::lang_cxx;
5156 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005157 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005158 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005159 }
Mike Stump11289f42009-09-09 15:08:12 +00005160
Chris Lattner438e5012008-12-17 07:13:27 +00005161 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005162
Douglas Gregor07665a62009-01-05 19:45:36 +00005163 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005164 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005165 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005166 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005167 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005168 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005169}
5170
Douglas Gregor07665a62009-01-05 19:45:36 +00005171/// ActOnFinishLinkageSpecification - Completely the definition of
5172/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5173/// valid, it's the position of the closing '}' brace in a linkage
5174/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005175Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5176 DeclPtrTy LinkageSpec,
5177 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005178 if (LinkageSpec)
5179 PopDeclContext();
5180 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005181}
5182
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005183/// \brief Perform semantic analysis for the variable declaration that
5184/// occurs within a C++ catch clause, returning the newly-created
5185/// variable.
5186VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005187 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005188 IdentifierInfo *Name,
5189 SourceLocation Loc,
5190 SourceRange Range) {
5191 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005192
5193 // Arrays and functions decay.
5194 if (ExDeclType->isArrayType())
5195 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5196 else if (ExDeclType->isFunctionType())
5197 ExDeclType = Context.getPointerType(ExDeclType);
5198
5199 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5200 // The exception-declaration shall not denote a pointer or reference to an
5201 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005202 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005203 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005204 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005205 Invalid = true;
5206 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005207
Douglas Gregor104ee002010-03-08 01:47:36 +00005208 // GCC allows catching pointers and references to incomplete types
5209 // as an extension; so do we, but we warn by default.
5210
Sebastian Redl54c04d42008-12-22 19:15:10 +00005211 QualType BaseType = ExDeclType;
5212 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005213 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005214 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005215 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005216 BaseType = Ptr->getPointeeType();
5217 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005218 DK = diag::ext_catch_incomplete_ptr;
5219 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005220 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005221 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005222 BaseType = Ref->getPointeeType();
5223 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005224 DK = diag::ext_catch_incomplete_ref;
5225 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005226 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005227 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005228 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5229 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005230 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005231
Mike Stump11289f42009-09-09 15:08:12 +00005232 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005233 RequireNonAbstractType(Loc, ExDeclType,
5234 diag::err_abstract_type_in_decl,
5235 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005236 Invalid = true;
5237
Mike Stump11289f42009-09-09 15:08:12 +00005238 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00005239 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005240
Douglas Gregor6de584c2010-03-05 23:38:39 +00005241 if (!Invalid) {
5242 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5243 // C++ [except.handle]p16:
5244 // The object declared in an exception-declaration or, if the
5245 // exception-declaration does not specify a name, a temporary (12.2) is
5246 // copy-initialized (8.5) from the exception object. [...]
5247 // The object is destroyed when the handler exits, after the destruction
5248 // of any automatic objects initialized within the handler.
5249 //
5250 // We just pretend to initialize the object with itself, then make sure
5251 // it can be destroyed later.
5252 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5253 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5254 Loc, ExDeclType, 0);
5255 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5256 SourceLocation());
5257 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5258 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5259 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5260 if (Result.isInvalid())
5261 Invalid = true;
5262 else
5263 FinalizeVarWithDestructor(ExDecl, RecordTy);
5264 }
5265 }
5266
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005267 if (Invalid)
5268 ExDecl->setInvalidDecl();
5269
5270 return ExDecl;
5271}
5272
5273/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5274/// handler.
5275Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005276 TypeSourceInfo *TInfo = 0;
5277 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005278
5279 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005280 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00005281 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005282 // The scope should be freshly made just for us. There is just no way
5283 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005284 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005285 if (PrevDecl->isTemplateParameter()) {
5286 // Maybe we will complain about the shadowed template parameter.
5287 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005288 }
5289 }
5290
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005291 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005292 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5293 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005294 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005295 }
5296
John McCallbcd03502009-12-07 02:54:59 +00005297 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005298 D.getIdentifier(),
5299 D.getIdentifierLoc(),
5300 D.getDeclSpec().getSourceRange());
5301
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005302 if (Invalid)
5303 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005304
Sebastian Redl54c04d42008-12-22 19:15:10 +00005305 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005306 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005307 PushOnScopeChains(ExDecl, S);
5308 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005309 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005310
Douglas Gregor758a8692009-06-17 21:51:59 +00005311 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005312 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005313}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005314
Mike Stump11289f42009-09-09 15:08:12 +00005315Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005316 ExprArg assertexpr,
5317 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005318 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005319 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005320 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5321
Anders Carlsson54b26982009-03-14 00:33:21 +00005322 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5323 llvm::APSInt Value(32);
5324 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5325 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5326 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005327 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005328 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005329
Anders Carlsson54b26982009-03-14 00:33:21 +00005330 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005331 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005332 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005333 }
5334 }
Mike Stump11289f42009-09-09 15:08:12 +00005335
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005336 assertexpr.release();
5337 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005338 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005339 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005340
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005341 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005342 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005343}
Sebastian Redlf769df52009-03-24 22:27:57 +00005344
John McCall11083da2009-09-16 22:47:08 +00005345/// Handle a friend type declaration. This works in tandem with
5346/// ActOnTag.
5347///
5348/// Notes on friend class templates:
5349///
5350/// We generally treat friend class declarations as if they were
5351/// declaring a class. So, for example, the elaborated type specifier
5352/// in a friend declaration is required to obey the restrictions of a
5353/// class-head (i.e. no typedefs in the scope chain), template
5354/// parameters are required to match up with simple template-ids, &c.
5355/// However, unlike when declaring a template specialization, it's
5356/// okay to refer to a template specialization without an empty
5357/// template parameter declaration, e.g.
5358/// friend class A<T>::B<unsigned>;
5359/// We permit this as a special case; if there are any template
5360/// parameters present at all, require proper matching, i.e.
5361/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005362Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005363 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005364 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005365
5366 assert(DS.isFriendSpecified());
5367 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5368
John McCall11083da2009-09-16 22:47:08 +00005369 // Try to convert the decl specifier to a type. This works for
5370 // friend templates because ActOnTag never produces a ClassTemplateDecl
5371 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005372 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005373 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5374 if (TheDeclarator.isInvalidType())
5375 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005376
John McCall11083da2009-09-16 22:47:08 +00005377 // This is definitely an error in C++98. It's probably meant to
5378 // be forbidden in C++0x, too, but the specification is just
5379 // poorly written.
5380 //
5381 // The problem is with declarations like the following:
5382 // template <T> friend A<T>::foo;
5383 // where deciding whether a class C is a friend or not now hinges
5384 // on whether there exists an instantiation of A that causes
5385 // 'foo' to equal C. There are restrictions on class-heads
5386 // (which we declare (by fiat) elaborated friend declarations to
5387 // be) that makes this tractable.
5388 //
5389 // FIXME: handle "template <> friend class A<T>;", which
5390 // is possibly well-formed? Who even knows?
5391 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5392 Diag(Loc, diag::err_tagless_friend_type_template)
5393 << DS.getSourceRange();
5394 return DeclPtrTy();
5395 }
5396
John McCallaa74a0c2009-08-28 07:59:38 +00005397 // C++ [class.friend]p2:
5398 // An elaborated-type-specifier shall be used in a friend declaration
5399 // for a class.*
5400 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00005401 // This is one of the rare places in Clang where it's legitimate to
5402 // ask about the "spelling" of the type.
5403 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5404 // If we evaluated the type to a record type, suggest putting
5405 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00005406 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00005407 RecordDecl *RD = RT->getDecl();
5408
5409 std::string InsertionText = std::string(" ") + RD->getKindName();
5410
John McCallc3987482009-10-07 23:34:25 +00005411 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5412 << (unsigned) RD->getTagKind()
5413 << T
5414 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00005415 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5416 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00005417 return DeclPtrTy();
5418 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00005419 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5420 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005421 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00005422 }
5423 }
5424
John McCallc3987482009-10-07 23:34:25 +00005425 // Enum types cannot be friends.
5426 if (T->getAs<EnumType>()) {
5427 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5428 << SourceRange(DS.getFriendSpecLoc());
5429 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00005430 }
John McCallaa74a0c2009-08-28 07:59:38 +00005431
John McCallaa74a0c2009-08-28 07:59:38 +00005432 // C++98 [class.friend]p1: A friend of a class is a function
5433 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005434 // This is fixed in DR77, which just barely didn't make the C++03
5435 // deadline. It's also a very silly restriction that seriously
5436 // affects inner classes and which nobody else seems to implement;
5437 // thus we never diagnose it, not even in -pedantic.
John McCallaa74a0c2009-08-28 07:59:38 +00005438
John McCall11083da2009-09-16 22:47:08 +00005439 Decl *D;
5440 if (TempParams.size())
5441 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5442 TempParams.size(),
5443 (TemplateParameterList**) TempParams.release(),
5444 T.getTypePtr(),
5445 DS.getFriendSpecLoc());
5446 else
5447 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5448 DS.getFriendSpecLoc());
5449 D->setAccess(AS_public);
5450 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005451
John McCall11083da2009-09-16 22:47:08 +00005452 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005453}
5454
John McCall2f212b32009-09-11 21:02:39 +00005455Sema::DeclPtrTy
5456Sema::ActOnFriendFunctionDecl(Scope *S,
5457 Declarator &D,
5458 bool IsDefinition,
5459 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005460 const DeclSpec &DS = D.getDeclSpec();
5461
5462 assert(DS.isFriendSpecified());
5463 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5464
5465 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005466 TypeSourceInfo *TInfo = 0;
5467 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005468
5469 // C++ [class.friend]p1
5470 // A friend of a class is a function or class....
5471 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005472 // It *doesn't* see through dependent types, which is correct
5473 // according to [temp.arg.type]p3:
5474 // If a declaration acquires a function type through a
5475 // type dependent on a template-parameter and this causes
5476 // a declaration that does not use the syntactic form of a
5477 // function declarator to have a function type, the program
5478 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005479 if (!T->isFunctionType()) {
5480 Diag(Loc, diag::err_unexpected_friend);
5481
5482 // It might be worthwhile to try to recover by creating an
5483 // appropriate declaration.
5484 return DeclPtrTy();
5485 }
5486
5487 // C++ [namespace.memdef]p3
5488 // - If a friend declaration in a non-local class first declares a
5489 // class or function, the friend class or function is a member
5490 // of the innermost enclosing namespace.
5491 // - The name of the friend is not found by simple name lookup
5492 // until a matching declaration is provided in that namespace
5493 // scope (either before or after the class declaration granting
5494 // friendship).
5495 // - If a friend function is called, its name may be found by the
5496 // name lookup that considers functions from namespaces and
5497 // classes associated with the types of the function arguments.
5498 // - When looking for a prior declaration of a class or a function
5499 // declared as a friend, scopes outside the innermost enclosing
5500 // namespace scope are not considered.
5501
John McCallaa74a0c2009-08-28 07:59:38 +00005502 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5503 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005504 assert(Name);
5505
John McCall07e91c02009-08-06 02:15:43 +00005506 // The context we found the declaration in, or in which we should
5507 // create the declaration.
5508 DeclContext *DC;
5509
5510 // FIXME: handle local classes
5511
5512 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005513 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5514 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005515 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005516 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00005517 DC = computeDeclContext(ScopeQual);
5518
5519 // FIXME: handle dependent contexts
5520 if (!DC) return DeclPtrTy();
5521
John McCall1f82f242009-11-18 22:49:29 +00005522 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005523
5524 // If searching in that context implicitly found a declaration in
5525 // a different context, treat it like it wasn't found at all.
5526 // TODO: better diagnostics for this case. Suggesting the right
5527 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005528 // FIXME: getRepresentativeDecl() is not right here at all
5529 if (Previous.empty() ||
5530 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005531 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005532 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5533 return DeclPtrTy();
5534 }
5535
5536 // C++ [class.friend]p1: A friend of a class is a function or
5537 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005538 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005539 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5540
John McCall07e91c02009-08-06 02:15:43 +00005541 // Otherwise walk out to the nearest namespace scope looking for matches.
5542 } else {
5543 // TODO: handle local class contexts.
5544
5545 DC = CurContext;
5546 while (true) {
5547 // Skip class contexts. If someone can cite chapter and verse
5548 // for this behavior, that would be nice --- it's what GCC and
5549 // EDG do, and it seems like a reasonable intent, but the spec
5550 // really only says that checks for unqualified existing
5551 // declarations should stop at the nearest enclosing namespace,
5552 // not that they should only consider the nearest enclosing
5553 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005554 while (DC->isRecord())
5555 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005556
John McCall1f82f242009-11-18 22:49:29 +00005557 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005558
5559 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005560 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005561 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005562
John McCall07e91c02009-08-06 02:15:43 +00005563 if (DC->isFileContext()) break;
5564 DC = DC->getParent();
5565 }
5566
5567 // C++ [class.friend]p1: A friend of a class is a function or
5568 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005569 // C++0x changes this for both friend types and functions.
5570 // Most C++ 98 compilers do seem to give an error here, so
5571 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005572 if (!Previous.empty() && DC->Equals(CurContext)
5573 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005574 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5575 }
5576
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005577 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005578 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005579 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5580 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5581 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005582 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005583 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5584 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005585 return DeclPtrTy();
5586 }
John McCall07e91c02009-08-06 02:15:43 +00005587 }
5588
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005589 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005590 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005591 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005592 IsDefinition,
5593 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005594 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005595
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005596 assert(ND->getDeclContext() == DC);
5597 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005598
John McCall759e32b2009-08-31 22:39:49 +00005599 // Add the function declaration to the appropriate lookup tables,
5600 // adjusting the redeclarations list as necessary. We don't
5601 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005602 //
John McCall759e32b2009-08-31 22:39:49 +00005603 // Also update the scope-based lookup if the target context's
5604 // lookup context is in lexical scope.
5605 if (!CurContext->isDependentContext()) {
5606 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005607 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005608 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005609 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005610 }
John McCallaa74a0c2009-08-28 07:59:38 +00005611
5612 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005613 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005614 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005615 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005616 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005617
Douglas Gregor33636e62009-12-24 20:56:24 +00005618 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5619 FrD->setSpecialization(true);
5620
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005621 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005622}
5623
Chris Lattner83f095c2009-03-28 19:18:32 +00005624void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005625 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005626
Chris Lattner83f095c2009-03-28 19:18:32 +00005627 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005628 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5629 if (!Fn) {
5630 Diag(DelLoc, diag::err_deleted_non_function);
5631 return;
5632 }
5633 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5634 Diag(DelLoc, diag::err_deleted_decl_not_first);
5635 Diag(Prev->getLocation(), diag::note_previous_declaration);
5636 // If the declaration wasn't the first, we delete the function anyway for
5637 // recovery.
5638 }
5639 Fn->setDeleted();
5640}
Sebastian Redl4c018662009-04-27 21:33:24 +00005641
5642static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5643 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5644 ++CI) {
5645 Stmt *SubStmt = *CI;
5646 if (!SubStmt)
5647 continue;
5648 if (isa<ReturnStmt>(SubStmt))
5649 Self.Diag(SubStmt->getSourceRange().getBegin(),
5650 diag::err_return_in_constructor_handler);
5651 if (!isa<Expr>(SubStmt))
5652 SearchForReturnInStmt(Self, SubStmt);
5653 }
5654}
5655
5656void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5657 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5658 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5659 SearchForReturnInStmt(*this, Handler);
5660 }
5661}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005662
Mike Stump11289f42009-09-09 15:08:12 +00005663bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005664 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005665 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5666 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005667
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005668 if (Context.hasSameType(NewTy, OldTy) ||
5669 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005670 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005671
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005672 // Check if the return types are covariant
5673 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005674
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005675 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005676 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5677 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005678 NewClassTy = NewPT->getPointeeType();
5679 OldClassTy = OldPT->getPointeeType();
5680 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005681 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5682 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5683 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5684 NewClassTy = NewRT->getPointeeType();
5685 OldClassTy = OldRT->getPointeeType();
5686 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005687 }
5688 }
Mike Stump11289f42009-09-09 15:08:12 +00005689
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005690 // The return types aren't either both pointers or references to a class type.
5691 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005692 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005693 diag::err_different_return_type_for_overriding_virtual_function)
5694 << New->getDeclName() << NewTy << OldTy;
5695 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005696
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005697 return true;
5698 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005699
Anders Carlssone60365b2009-12-31 18:34:24 +00005700 // C++ [class.virtual]p6:
5701 // If the return type of D::f differs from the return type of B::f, the
5702 // class type in the return type of D::f shall be complete at the point of
5703 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005704 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5705 if (!RT->isBeingDefined() &&
5706 RequireCompleteType(New->getLocation(), NewClassTy,
5707 PDiag(diag::err_covariant_return_incomplete)
5708 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005709 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005710 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005711
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005712 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005713 // Check if the new class derives from the old class.
5714 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5715 Diag(New->getLocation(),
5716 diag::err_covariant_return_not_derived)
5717 << New->getDeclName() << NewTy << OldTy;
5718 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5719 return true;
5720 }
Mike Stump11289f42009-09-09 15:08:12 +00005721
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005722 // Check if we the conversion from derived to base is valid.
John McCall5b0829a2010-02-10 09:31:12 +00005723 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005724 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5725 // FIXME: Should this point to the return type?
5726 New->getLocation(), SourceRange(), New->getDeclName())) {
5727 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5728 return true;
5729 }
5730 }
Mike Stump11289f42009-09-09 15:08:12 +00005731
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005732 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005733 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005734 Diag(New->getLocation(),
5735 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005736 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005737 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5738 return true;
5739 };
Mike Stump11289f42009-09-09 15:08:12 +00005740
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005741
5742 // The new class type must have the same or less qualifiers as the old type.
5743 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5744 Diag(New->getLocation(),
5745 diag::err_covariant_return_type_class_type_more_qualified)
5746 << New->getDeclName() << NewTy << OldTy;
5747 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5748 return true;
5749 };
Mike Stump11289f42009-09-09 15:08:12 +00005750
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005751 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005752}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005753
Alexis Hunt96d5c762009-11-21 08:43:09 +00005754bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5755 const CXXMethodDecl *Old)
5756{
5757 if (Old->hasAttr<FinalAttr>()) {
5758 Diag(New->getLocation(), diag::err_final_function_overridden)
5759 << New->getDeclName();
5760 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5761 return true;
5762 }
5763
5764 return false;
5765}
5766
Douglas Gregor21920e372009-12-01 17:24:26 +00005767/// \brief Mark the given method pure.
5768///
5769/// \param Method the method to be marked pure.
5770///
5771/// \param InitRange the source range that covers the "0" initializer.
5772bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5773 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5774 Method->setPure();
5775
5776 // A class is abstract if at least one function is pure virtual.
5777 Method->getParent()->setAbstract(true);
5778 return false;
5779 }
5780
5781 if (!Method->isInvalidDecl())
5782 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5783 << Method->getDeclName() << InitRange;
5784 return true;
5785}
5786
John McCall1f4ee7b2009-12-19 09:28:58 +00005787/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5788/// an initializer for the out-of-line declaration 'Dcl'. The scope
5789/// is a fresh scope pushed for just this purpose.
5790///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005791/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5792/// static data member of class X, names should be looked up in the scope of
5793/// class X.
5794void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005795 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005796 Decl *D = Dcl.getAs<Decl>();
5797 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005798
John McCall1f4ee7b2009-12-19 09:28:58 +00005799 // We should only get called for declarations with scope specifiers, like:
5800 // int foo::bar;
5801 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005802 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005803}
5804
5805/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005806/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005807void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005808 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005809 Decl *D = Dcl.getAs<Decl>();
5810 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005811
John McCall1f4ee7b2009-12-19 09:28:58 +00005812 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005813 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005814}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005815
5816/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5817/// C++ if/switch/while/for statement.
5818/// e.g: "if (int x = f()) {...}"
5819Action::DeclResult
5820Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5821 // C++ 6.4p2:
5822 // The declarator shall not specify a function or an array.
5823 // The type-specifier-seq shall not contain typedef and shall not declare a
5824 // new class or enumeration.
5825 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5826 "Parser allowed 'typedef' as storage class of condition decl.");
5827
John McCallbcd03502009-12-07 02:54:59 +00005828 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005829 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005830 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005831
5832 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5833 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5834 // would be created and CXXConditionDeclExpr wants a VarDecl.
5835 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5836 << D.getSourceRange();
5837 return DeclResult();
5838 } else if (OwnedTag && OwnedTag->isDefinition()) {
5839 // The type-specifier-seq shall not declare a new class or enumeration.
5840 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5841 }
5842
5843 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5844 if (!Dcl)
5845 return DeclResult();
5846
5847 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5848 VD->setDeclaredInCondition(true);
5849 return Dcl;
5850}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005851
Rafael Espindola70e040d2010-03-02 21:28:26 +00005852static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005853 // Ignore dependent types.
5854 if (MD->isDependentContext())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005855 return false;
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005856
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005857 // Ignore declarations that are not definitions.
5858 if (!MD->isThisDeclarationADefinition())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005859 return false;
5860
5861 CXXRecordDecl *RD = MD->getParent();
5862
5863 // Ignore classes without a vtable.
5864 if (!RD->isDynamicClass())
5865 return false;
5866
5867 switch (MD->getParent()->getTemplateSpecializationKind()) {
5868 case TSK_Undeclared:
5869 case TSK_ExplicitSpecialization:
5870 // Classes that aren't instantiations of templates don't need their
5871 // virtual methods marked until we see the definition of the key
5872 // function.
5873 break;
5874
5875 case TSK_ImplicitInstantiation:
5876 // This is a constructor of a class template; mark all of the virtual
5877 // members as referenced to ensure that they get instantiatied.
5878 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5879 return true;
5880 break;
5881
5882 case TSK_ExplicitInstantiationDeclaration:
5883 return true; //FIXME: This looks wrong.
5884
5885 case TSK_ExplicitInstantiationDefinition:
5886 // This is method of a explicit instantiation; mark all of the virtual
5887 // members as referenced to ensure that they get instantiatied.
5888 return true;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005889 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00005890
5891 // Consider only out-of-line definitions of member functions. When we see
5892 // an inline definition, it's too early to compute the key function.
5893 if (!MD->isOutOfLine())
5894 return false;
5895
5896 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5897
5898 // If there is no key function, we will need a copy of the vtable.
5899 if (!KeyFunction)
5900 return true;
5901
5902 // If this is the key function, we need to mark virtual members.
5903 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5904 return true;
5905
5906 return false;
5907}
5908
5909void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5910 CXXMethodDecl *MD) {
5911 CXXRecordDecl *RD = MD->getParent();
5912
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005913 // We will need to mark all of the virtual members as referenced to build the
5914 // vtable.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00005915 if (!needsVtable(MD, Context))
5916 return;
5917
5918 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5919 if (kind == TSK_ImplicitInstantiation)
5920 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5921 else
Rafael Espindola70e040d2010-03-02 21:28:26 +00005922 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson82fccd02009-12-07 08:24:59 +00005923}
5924
5925bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5926 if (ClassesWithUnmarkedVirtualMembers.empty())
5927 return false;
5928
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005929 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5930 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5931 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5932 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00005933 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005934 }
5935
Anders Carlsson82fccd02009-12-07 08:24:59 +00005936 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00005937}
Anders Carlsson82fccd02009-12-07 08:24:59 +00005938
5939void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5940 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5941 e = RD->method_end(); i != e; ++i) {
5942 CXXMethodDecl *MD = *i;
5943
5944 // C++ [basic.def.odr]p2:
5945 // [...] A virtual member function is used if it is not pure. [...]
5946 if (MD->isVirtual() && !MD->isPure())
5947 MarkDeclarationReferenced(Loc, MD);
5948 }
5949}