blob: fb0e1440365851709f900f869ba0ef3bca0c56dd [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000028#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000029
30using namespace clang;
31
Chris Lattner8123a952008-04-10 02:22:51 +000032//===----------------------------------------------------------------------===//
33// CheckDefaultArgumentVisitor
34//===----------------------------------------------------------------------===//
35
Chris Lattner9e979552008-04-12 23:52:44 +000036namespace {
37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
38 /// the default argument of a parameter to determine whether it
39 /// contains any ill-formed subexpressions. For example, this will
40 /// diagnose the use of local variables or parameters within the
41 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000042 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000043 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000044 Expr *DefaultArg;
45 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000046
Chris Lattner9e979552008-04-12 23:52:44 +000047 public:
Mike Stump1eb44332009-09-09 15:08:12 +000048 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000049 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 bool VisitExpr(Expr *Node);
52 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000053 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000054 };
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 /// VisitExpr - Visit all of the children of this expression.
57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
58 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000059 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000060 E = Node->child_end(); I != E; ++I)
61 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000062 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000063 }
64
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitDeclRefExpr - Visit a reference to a declaration, to
66 /// determine whether this declaration can be used in the default
67 /// argument expression.
68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000069 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000070 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
71 // C++ [dcl.fct.default]p9
72 // Default arguments are evaluated each time the function is
73 // called. The order of evaluation of function arguments is
74 // unspecified. Consequently, parameters of a function shall not
75 // be used in default argument expressions, even if they are not
76 // evaluated. Parameters of a function declared before a default
77 // argument expression are in scope and can hide namespace and
78 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000079 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000080 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000081 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000082 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000083 // C++ [dcl.fct.default]p7
84 // Local variables shall not be used in default argument
85 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000086 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000090 }
Chris Lattner8123a952008-04-10 02:22:51 +000091
Douglas Gregor3996f232008-11-04 13:41:56 +000092 return false;
93 }
Chris Lattner9e979552008-04-12 23:52:44 +000094
Douglas Gregor796da182008-11-04 14:32:21 +000095 /// VisitCXXThisExpr - Visit a C++ "this" expression.
96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
97 // C++ [dcl.fct.default]p8:
98 // The keyword this shall not be used in a default argument of a
99 // member function.
100 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_this)
102 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104}
105
Anders Carlssoned961f92009-08-25 02:29:20 +0000106bool
107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000108 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000109 QualType ParamType = Param->getType();
110
Anders Carlsson5653ca52009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssoned961f92009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000127 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Anders Carlssoned961f92009-08-25 02:29:20 +0000131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Anders Carlssoned961f92009-08-25 02:29:20 +0000134 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000137}
138
Chris Lattner8123a952008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142void
Mike Stump1eb44332009-09-09 15:08:12 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattnerb28317a2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlsson66e30672009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Anders Carlssoned961f92009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000170}
171
Douglas Gregor61366e92008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000179 if (!param)
180 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Anders Carlsson5e300d12009-06-12 16:51:40 +0000186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187}
188
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000192 if (!param)
193 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson5e300d12009-06-12 16:51:40 +0000197 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Anders Carlsson5e300d12009-06-12 16:51:40 +0000199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000200}
201
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000256 //
257 // C++ [dcl.fct.default]p6:
258 // Except for member functions of class templates, the default arguments
259 // in a member function definition that appears outside of the class
260 // definition are added to the set of default arguments provided by the
261 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
263 ParmVarDecl *OldParam = Old->getParamDecl(p);
264 ParmVarDecl *NewParam = New->getParamDecl(p);
265
Douglas Gregor6cc15182009-09-11 18:44:32 +0000266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000267 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000268 diag::err_param_default_argument_redefinition)
Douglas Gregor6cc15182009-09-11 18:44:32 +0000269 << NewParam->getDefaultArgRange();
270
271 // Look for the function declaration where the default argument was
272 // actually written, which may be a declaration prior to Old.
273 for (FunctionDecl *Older = Old->getPreviousDeclaration();
274 Older; Older = Older->getPreviousDeclaration()) {
275 if (!Older->getParamDecl(p)->hasDefaultArg())
276 break;
277
278 OldParam = Older->getParamDecl(p);
279 }
280
281 Diag(OldParam->getLocation(), diag::note_previous_definition)
282 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000283 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000284 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000285 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000286 if (OldParam->hasUninstantiatedDefaultArg())
287 NewParam->setUninstantiatedDefaultArg(
288 OldParam->getUninstantiatedDefaultArg());
289 else
290 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000291 } else if (NewParam->hasDefaultArg()) {
292 if (New->getDescribedFunctionTemplate()) {
293 // Paragraph 4, quoted above, only applies to non-template functions.
294 Diag(NewParam->getLocation(),
295 diag::err_param_default_argument_template_redecl)
296 << NewParam->getDefaultArgRange();
297 Diag(Old->getLocation(), diag::note_template_prev_declaration)
298 << false;
299 } else if (New->getDeclContext()->isDependentContext()) {
300 // C++ [dcl.fct.default]p6 (DR217):
301 // Default arguments for a member function of a class template shall
302 // be specified on the initial declaration of the member function
303 // within the class template.
304 //
305 // Reading the tea leaves a bit in DR217 and its reference to DR205
306 // leads me to the conclusion that one cannot add default function
307 // arguments for an out-of-line definition of a member function of a
308 // dependent type.
309 int WhichKind = 2;
310 if (CXXRecordDecl *Record
311 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
312 if (Record->getDescribedClassTemplate())
313 WhichKind = 0;
314 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
315 WhichKind = 1;
316 else
317 WhichKind = 2;
318 }
319
320 Diag(NewParam->getLocation(),
321 diag::err_param_default_argument_member_template_redecl)
322 << WhichKind
323 << NewParam->getDefaultArgRange();
324 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000325 }
326 }
327
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000328 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000329 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
330 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000331 Invalid = true;
332 }
333
Douglas Gregorcda9c672009-02-16 17:45:42 +0000334 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000335}
336
337/// CheckCXXDefaultArguments - Verify that the default arguments for a
338/// function declaration are well-formed according to C++
339/// [dcl.fct.default].
340void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
341 unsigned NumParams = FD->getNumParams();
342 unsigned p;
343
344 // Find first parameter with a default argument
345 for (p = 0; p < NumParams; ++p) {
346 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000347 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000348 break;
349 }
350
351 // C++ [dcl.fct.default]p4:
352 // In a given function declaration, all parameters
353 // subsequent to a parameter with a default argument shall
354 // have default arguments supplied in this or previous
355 // declarations. A default argument shall not be redefined
356 // by a later declaration (not even to the same value).
357 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000358 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000359 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000360 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000361 if (Param->isInvalidDecl())
362 /* We already complained about this parameter. */;
363 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000364 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000365 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000366 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000367 else
Mike Stump1eb44332009-09-09 15:08:12 +0000368 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000369 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Chris Lattner3d1cee32008-04-08 05:04:30 +0000371 LastMissingDefaultArg = p;
372 }
373 }
374
375 if (LastMissingDefaultArg > 0) {
376 // Some default arguments were missing. Clear out all of the
377 // default arguments up to (and including) the last missing
378 // default argument, so that we leave the function parameters
379 // in a semantically valid state.
380 for (p = 0; p <= LastMissingDefaultArg; ++p) {
381 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000382 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000383 if (!Param->hasUnparsedDefaultArg())
384 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 Param->setDefaultArg(0);
386 }
387 }
388 }
389}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000390
Douglas Gregorb48fe382008-10-31 09:07:45 +0000391/// isCurrentClassName - Determine whether the identifier II is the
392/// name of the class type currently being defined. In the case of
393/// nested classes, this will only return true if II is the name of
394/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000395bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
396 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000397 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000398 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000399 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000400 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
401 } else
402 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
403
404 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000405 return &II == CurDecl->getIdentifier();
406 else
407 return false;
408}
409
Mike Stump1eb44332009-09-09 15:08:12 +0000410/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000411///
412/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
413/// and returns NULL otherwise.
414CXXBaseSpecifier *
415Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
416 SourceRange SpecifierRange,
417 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000418 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000419 SourceLocation BaseLoc) {
420 // C++ [class.union]p1:
421 // A union shall not have base classes.
422 if (Class->isUnion()) {
423 Diag(Class->getLocation(), diag::err_base_clause_on_union)
424 << SpecifierRange;
425 return 0;
426 }
427
428 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000429 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000430 Class->getTagKind() == RecordDecl::TK_class,
431 Access, BaseType);
432
433 // Base specifiers must be record types.
434 if (!BaseType->isRecordType()) {
435 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
436 return 0;
437 }
438
439 // C++ [class.union]p1:
440 // A union shall not be used as a base class.
441 if (BaseType->isUnionType()) {
442 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
443 return 0;
444 }
445
446 // C++ [class.derived]p2:
447 // The class-name in a base-specifier shall not be an incompletely
448 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000449 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000450 PDiag(diag::err_incomplete_base_class)
451 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000452 return 0;
453
Eli Friedman1d954f62009-08-15 21:55:26 +0000454 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000455 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000456 assert(BaseDecl && "Record type has no declaration");
457 BaseDecl = BaseDecl->getDefinition(Context);
458 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000459 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
460 assert(CXXBaseDecl && "Base type is not a C++ type");
461 if (!CXXBaseDecl->isEmpty())
462 Class->setEmpty(false);
463 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000464 Class->setPolymorphic(true);
465
466 // C++ [dcl.init.aggr]p1:
467 // An aggregate is [...] a class with [...] no base classes [...].
468 Class->setAggregate(false);
469 Class->setPOD(false);
470
Anders Carlsson347ba892009-04-16 00:08:20 +0000471 if (Virtual) {
472 // C++ [class.ctor]p5:
473 // A constructor is trivial if its class has no virtual base classes.
474 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000475
476 // C++ [class.copy]p6:
477 // A copy constructor is trivial if its class has no virtual base classes.
478 Class->setHasTrivialCopyConstructor(false);
479
480 // C++ [class.copy]p11:
481 // A copy assignment operator is trivial if its class has no virtual
482 // base classes.
483 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000484
485 // C++0x [meta.unary.prop] is_empty:
486 // T is a class type, but not a union type, with ... no virtual base
487 // classes
488 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000489 } else {
490 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000491 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000492 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000493 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
494 Class->setHasTrivialConstructor(false);
495
496 // C++ [class.copy]p6:
497 // A copy constructor is trivial if all the direct base classes of its
498 // class have trivial copy constructors.
499 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
500 Class->setHasTrivialCopyConstructor(false);
501
502 // C++ [class.copy]p11:
503 // A copy assignment operator is trivial if all the direct base classes
504 // of its class have trivial copy assignment operators.
505 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
506 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000507 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000508
509 // C++ [class.ctor]p3:
510 // A destructor is trivial if all the direct base classes of its class
511 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000512 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
513 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor2943aed2009-03-03 04:44:36 +0000515 // Create the base specifier.
516 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000517 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
518 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000519 Access, BaseType);
520}
521
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000522/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
523/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000524/// example:
525/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000526/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000527Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000528Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000529 bool Virtual, AccessSpecifier Access,
530 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000531 if (!classdecl)
532 return true;
533
Douglas Gregor40808ce2009-03-09 23:48:35 +0000534 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000535 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000536 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000537 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
538 Virtual, Access,
539 BaseType, BaseLoc))
540 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Douglas Gregor2943aed2009-03-03 04:44:36 +0000542 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000543}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000544
Douglas Gregor2943aed2009-03-03 04:44:36 +0000545/// \brief Performs the actual work of attaching the given base class
546/// specifiers to a C++ class.
547bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
548 unsigned NumBases) {
549 if (NumBases == 0)
550 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000551
552 // Used to keep track of which base types we have already seen, so
553 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000554 // that the key is always the unqualified canonical type of the base
555 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000556 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
557
558 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000559 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000560 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000561 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000564 NewBaseType = NewBaseType.getUnqualifiedType();
565
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000566 if (KnownBaseTypes[NewBaseType]) {
567 // C++ [class.mi]p3:
568 // A class shall not be specified as a direct base class of a
569 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000571 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000572 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000574
575 // Delete the duplicate base class specifier; we're going to
576 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000577 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000578
579 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000580 } else {
581 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 KnownBaseTypes[NewBaseType] = Bases[idx];
583 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000584 }
585 }
586
587 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000588 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000589
590 // Delete the remaining (good) base class specifiers, since their
591 // data has been copied into the CXXRecordDecl.
592 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000593 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594
595 return Invalid;
596}
597
598/// ActOnBaseSpecifiers - Attach the given base specifiers to the
599/// class, after checking whether there are any duplicate base
600/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000601void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000602 unsigned NumBases) {
603 if (!ClassDecl || !Bases || !NumBases)
604 return;
605
606 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000607 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000609}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000610
Douglas Gregora8f32e02009-10-06 17:59:45 +0000611/// \brief Determine whether the type \p Derived is a C++ class that is
612/// derived from the type \p Base.
613bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
614 if (!getLangOptions().CPlusPlus)
615 return false;
616
617 const RecordType *DerivedRT = Derived->getAs<RecordType>();
618 if (!DerivedRT)
619 return false;
620
621 const RecordType *BaseRT = Base->getAs<RecordType>();
622 if (!BaseRT)
623 return false;
624
625 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
626 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
627 return DerivedRD->isDerivedFrom(BaseRD);
628}
629
630/// \brief Determine whether the type \p Derived is a C++ class that is
631/// derived from the type \p Base.
632bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
633 if (!getLangOptions().CPlusPlus)
634 return false;
635
636 const RecordType *DerivedRT = Derived->getAs<RecordType>();
637 if (!DerivedRT)
638 return false;
639
640 const RecordType *BaseRT = Base->getAs<RecordType>();
641 if (!BaseRT)
642 return false;
643
644 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
645 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
646 return DerivedRD->isDerivedFrom(BaseRD, Paths);
647}
648
649/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
650/// conversion (where Derived and Base are class types) is
651/// well-formed, meaning that the conversion is unambiguous (and
652/// that all of the base classes are accessible). Returns true
653/// and emits a diagnostic if the code is ill-formed, returns false
654/// otherwise. Loc is the location where this routine should point to
655/// if there is an error, and Range is the source range to highlight
656/// if there is an error.
657bool
658Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
659 unsigned InaccessibleBaseID,
660 unsigned AmbigiousBaseConvID,
661 SourceLocation Loc, SourceRange Range,
662 DeclarationName Name) {
663 // First, determine whether the path from Derived to Base is
664 // ambiguous. This is slightly more expensive than checking whether
665 // the Derived to Base conversion exists, because here we need to
666 // explore multiple paths to determine if there is an ambiguity.
667 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
668 /*DetectVirtual=*/false);
669 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
670 assert(DerivationOkay &&
671 "Can only be used with a derived-to-base conversion");
672 (void)DerivationOkay;
673
674 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
675 // Check that the base class can be accessed.
676 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
677 Name);
678 }
679
680 // We know that the derived-to-base conversion is ambiguous, and
681 // we're going to produce a diagnostic. Perform the derived-to-base
682 // search just one more time to compute all of the possible paths so
683 // that we can print them out. This is more expensive than any of
684 // the previous derived-to-base checks we've done, but at this point
685 // performance isn't as much of an issue.
686 Paths.clear();
687 Paths.setRecordingPaths(true);
688 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
689 assert(StillOkay && "Can only be used with a derived-to-base conversion");
690 (void)StillOkay;
691
692 // Build up a textual representation of the ambiguous paths, e.g.,
693 // D -> B -> A, that will be used to illustrate the ambiguous
694 // conversions in the diagnostic. We only print one of the paths
695 // to each base class subobject.
696 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
697
698 Diag(Loc, AmbigiousBaseConvID)
699 << Derived << Base << PathDisplayStr << Range << Name;
700 return true;
701}
702
703bool
704Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
705 SourceLocation Loc, SourceRange Range) {
706 return CheckDerivedToBaseConversion(Derived, Base,
707 diag::err_conv_to_inaccessible_base,
708 diag::err_ambiguous_derived_to_base_conv,
709 Loc, Range, DeclarationName());
710}
711
712
713/// @brief Builds a string representing ambiguous paths from a
714/// specific derived class to different subobjects of the same base
715/// class.
716///
717/// This function builds a string that can be used in error messages
718/// to show the different paths that one can take through the
719/// inheritance hierarchy to go from the derived class to different
720/// subobjects of a base class. The result looks something like this:
721/// @code
722/// struct D -> struct B -> struct A
723/// struct D -> struct C -> struct A
724/// @endcode
725std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
726 std::string PathDisplayStr;
727 std::set<unsigned> DisplayedPaths;
728 for (CXXBasePaths::paths_iterator Path = Paths.begin();
729 Path != Paths.end(); ++Path) {
730 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
731 // We haven't displayed a path to this particular base
732 // class subobject yet.
733 PathDisplayStr += "\n ";
734 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
735 for (CXXBasePath::const_iterator Element = Path->begin();
736 Element != Path->end(); ++Element)
737 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
738 }
739 }
740
741 return PathDisplayStr;
742}
743
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000744//===----------------------------------------------------------------------===//
745// C++ class member Handling
746//===----------------------------------------------------------------------===//
747
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000748/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
749/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
750/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000751/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000752Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000753Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000754 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000755 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000756 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000757 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000758 Expr *BitWidth = static_cast<Expr*>(BW);
759 Expr *Init = static_cast<Expr*>(InitExpr);
760 SourceLocation Loc = D.getIdentifierLoc();
761
Sebastian Redl669d5d72008-11-14 23:42:31 +0000762 bool isFunc = D.isFunctionDeclarator();
763
John McCall67d1a672009-08-06 02:15:43 +0000764 assert(!DS.isFriendSpecified());
765
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000766 // C++ 9.2p6: A member shall not be declared to have automatic storage
767 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000768 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
769 // data members and cannot be applied to names declared const or static,
770 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000771 switch (DS.getStorageClassSpec()) {
772 case DeclSpec::SCS_unspecified:
773 case DeclSpec::SCS_typedef:
774 case DeclSpec::SCS_static:
775 // FALL THROUGH.
776 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000777 case DeclSpec::SCS_mutable:
778 if (isFunc) {
779 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000780 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000781 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000782 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Sebastian Redla11f42f2008-11-17 23:24:37 +0000784 // FIXME: It would be nicer if the keyword was ignored only for this
785 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000786 D.getMutableDeclSpec().ClearStorageClassSpecs();
787 } else {
788 QualType T = GetTypeForDeclarator(D, S);
789 diag::kind err = static_cast<diag::kind>(0);
790 if (T->isReferenceType())
791 err = diag::err_mutable_reference;
792 else if (T.isConstQualified())
793 err = diag::err_mutable_const;
794 if (err != 0) {
795 if (DS.getStorageClassSpecLoc().isValid())
796 Diag(DS.getStorageClassSpecLoc(), err);
797 else
798 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000799 // FIXME: It would be nicer if the keyword was ignored only for this
800 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000801 D.getMutableDeclSpec().ClearStorageClassSpecs();
802 }
803 }
804 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000805 default:
806 if (DS.getStorageClassSpecLoc().isValid())
807 Diag(DS.getStorageClassSpecLoc(),
808 diag::err_storageclass_invalid_for_member);
809 else
810 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
811 D.getMutableDeclSpec().ClearStorageClassSpecs();
812 }
813
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000814 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000815 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000816 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000817 // Check also for this case:
818 //
819 // typedef int f();
820 // f a;
821 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000822 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000823 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000824 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000825
Sebastian Redl669d5d72008-11-14 23:42:31 +0000826 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
827 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000828 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829
830 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000831 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000832 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000833 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
834 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000835 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000836 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000837 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
838 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000839 if (!Member) {
840 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000841 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000842 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000843
844 // Non-instance-fields can't have a bitfield.
845 if (BitWidth) {
846 if (Member->isInvalidDecl()) {
847 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000848 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000849 // C++ 9.6p3: A bit-field shall not be a static member.
850 // "static member 'A' cannot be a bit-field"
851 Diag(Loc, diag::err_static_not_bitfield)
852 << Name << BitWidth->getSourceRange();
853 } else if (isa<TypedefDecl>(Member)) {
854 // "typedef member 'x' cannot be a bit-field"
855 Diag(Loc, diag::err_typedef_not_bitfield)
856 << Name << BitWidth->getSourceRange();
857 } else {
858 // A function typedef ("typedef int f(); f a;").
859 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
860 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000861 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000862 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Chris Lattner8b963ef2009-03-05 23:01:03 +0000865 DeleteExpr(BitWidth);
866 BitWidth = 0;
867 Member->setInvalidDecl();
868 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000869
870 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Douglas Gregor37b372b2009-08-20 22:52:58 +0000872 // If we have declared a member function template, set the access of the
873 // templated declaration as well.
874 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
875 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000876 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000877
Douglas Gregor10bd3682008-11-17 22:58:34 +0000878 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000879
Douglas Gregor021c3b32009-03-11 23:00:04 +0000880 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000881 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000882 if (Deleted) // FIXME: Source location is not very good.
883 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000885 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000886 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000887 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000889 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000890}
891
Douglas Gregor7ad83902008-11-05 04:29:56 +0000892/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000893Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000894Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000895 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000896 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000897 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000898 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000899 SourceLocation IdLoc,
900 SourceLocation LParenLoc,
901 ExprTy **Args, unsigned NumArgs,
902 SourceLocation *CommaLocs,
903 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000904 if (!ConstructorD)
905 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000907 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000908
909 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000910 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000911 if (!Constructor) {
912 // The user wrote a constructor initializer on a function that is
913 // not a C++ constructor. Ignore the error for now, because we may
914 // have more member initializers coming; we'll diagnose it just
915 // once in ActOnMemInitializers.
916 return true;
917 }
918
919 CXXRecordDecl *ClassDecl = Constructor->getParent();
920
921 // C++ [class.base.init]p2:
922 // Names in a mem-initializer-id are looked up in the scope of the
923 // constructor’s class and, if not found in that scope, are looked
924 // up in the scope containing the constructor’s
925 // definition. [Note: if the constructor’s class contains a member
926 // with the same name as a direct or virtual base class of the
927 // class, a mem-initializer-id naming the member or base class and
928 // composed of a single identifier refers to the class member. A
929 // mem-initializer-id for the hidden base class may be specified
930 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000931 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000932 // Look for a member, first.
933 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000934 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000935 = ClassDecl->lookup(MemberOrBase);
936 if (Result.first != Result.second)
937 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000938
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000939 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000940
Eli Friedman59c04372009-07-29 19:44:27 +0000941 if (Member)
942 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
943 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000944 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000945 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000946 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000947 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000948 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000949 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
950 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000952 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000953
Eli Friedman59c04372009-07-29 19:44:27 +0000954 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
955 RParenLoc, ClassDecl);
956}
957
958Sema::MemInitResult
959Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
960 unsigned NumArgs, SourceLocation IdLoc,
961 SourceLocation RParenLoc) {
962 bool HasDependentArg = false;
963 for (unsigned i = 0; i < NumArgs; i++)
964 HasDependentArg |= Args[i]->isTypeDependent();
965
966 CXXConstructorDecl *C = 0;
967 QualType FieldType = Member->getType();
968 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
969 FieldType = Array->getElementType();
970 if (FieldType->isDependentType()) {
971 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000972 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000973 if (!HasDependentArg) {
974 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
975
976 C = PerformInitializationByConstructor(FieldType,
977 MultiExprArg(*this,
978 (void**)Args,
979 NumArgs),
980 IdLoc,
981 SourceRange(IdLoc, RParenLoc),
982 Member->getDeclName(), IK_Direct,
983 ConstructorArgs);
984
985 if (C) {
986 // Take over the constructor arguments as our own.
987 NumArgs = ConstructorArgs.size();
988 Args = (Expr **)ConstructorArgs.take();
989 }
990 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000991 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000992 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +0000993 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
994 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000995 Expr *NewExp;
996 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000997 if (FieldType->isReferenceType()) {
998 Diag(IdLoc, diag::err_null_intialized_reference_member)
999 << Member->getDeclName();
1000 return Diag(Member->getLocation(), diag::note_declared_at);
1001 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001002 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1003 NumArgs = 1;
1004 }
1005 else
1006 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001007 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1008 return true;
1009 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001010 }
Eli Friedman59c04372009-07-29 19:44:27 +00001011 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001012 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001013 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001014}
1015
1016Sema::MemInitResult
1017Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1018 unsigned NumArgs, SourceLocation IdLoc,
1019 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1020 bool HasDependentArg = false;
1021 for (unsigned i = 0; i < NumArgs; i++)
1022 HasDependentArg |= Args[i]->isTypeDependent();
1023
1024 if (!BaseType->isDependentType()) {
1025 if (!BaseType->isRecordType())
1026 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1027 << BaseType << SourceRange(IdLoc, RParenLoc);
1028
1029 // C++ [class.base.init]p2:
1030 // [...] Unless the mem-initializer-id names a nonstatic data
1031 // member of the constructor’s class or a direct or virtual base
1032 // of that class, the mem-initializer is ill-formed. A
1033 // mem-initializer-list can initialize a base class using any
1034 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Eli Friedman59c04372009-07-29 19:44:27 +00001036 // First, check for a direct base class.
1037 const CXXBaseSpecifier *DirectBaseSpec = 0;
1038 for (CXXRecordDecl::base_class_const_iterator Base =
1039 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001040 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +00001041 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1042 // We found a direct base of this type. That's what we're
1043 // initializing.
1044 DirectBaseSpec = &*Base;
1045 break;
1046 }
1047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Eli Friedman59c04372009-07-29 19:44:27 +00001049 // Check for a virtual base class.
1050 // FIXME: We might be able to short-circuit this if we know in advance that
1051 // there are no virtual bases.
1052 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1053 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1054 // We haven't found a base yet; search the class hierarchy for a
1055 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001056 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1057 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001058 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001059 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001060 Path != Paths.end(); ++Path) {
1061 if (Path->back().Base->isVirtual()) {
1062 VirtualBaseSpec = Path->back().Base;
1063 break;
1064 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001065 }
1066 }
1067 }
Eli Friedman59c04372009-07-29 19:44:27 +00001068
1069 // C++ [base.class.init]p2:
1070 // If a mem-initializer-id is ambiguous because it designates both
1071 // a direct non-virtual base class and an inherited virtual base
1072 // class, the mem-initializer is ill-formed.
1073 if (DirectBaseSpec && VirtualBaseSpec)
1074 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1075 << BaseType << SourceRange(IdLoc, RParenLoc);
1076 // C++ [base.class.init]p2:
1077 // Unless the mem-initializer-id names a nonstatic data membeer of the
1078 // constructor's class ot a direst or virtual base of that class, the
1079 // mem-initializer is ill-formed.
1080 if (!DirectBaseSpec && !VirtualBaseSpec)
1081 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1082 << BaseType << ClassDecl->getNameAsCString()
1083 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001084 }
1085
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001086 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001087 if (!BaseType->isDependentType() && !HasDependentArg) {
1088 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
1089 Context.getCanonicalType(BaseType));
Douglas Gregor39da0b82009-09-09 23:08:42 +00001090 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1091
1092 C = PerformInitializationByConstructor(BaseType,
1093 MultiExprArg(*this,
1094 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001095 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001096 Name, IK_Direct,
1097 ConstructorArgs);
1098 if (C) {
1099 // Take over the constructor arguments as our own.
1100 NumArgs = ConstructorArgs.size();
1101 Args = (Expr **)ConstructorArgs.take();
1102 }
Eli Friedman59c04372009-07-29 19:44:27 +00001103 }
1104
Mike Stump1eb44332009-09-09 15:08:12 +00001105 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001106 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001107}
1108
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001109void
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001110Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1111 CXXBaseOrMemberInitializer **Initializers,
1112 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +00001113 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001114 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
1115 // We need to build the initializer AST according to order of construction
1116 // and not what user specified in the Initializers list.
1117 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1118 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1119 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1120 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001122 for (unsigned i = 0; i < NumInitializers; i++) {
1123 CXXBaseOrMemberInitializer *Member = Initializers[i];
1124 if (Member->isBaseInitializer()) {
1125 if (Member->getBaseClass()->isDependentType())
1126 HasDependentBaseInit = true;
1127 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1128 } else {
1129 AllBaseFields[Member->getMember()] = Member;
1130 }
1131 }
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001133 if (HasDependentBaseInit) {
1134 // FIXME. This does not preserve the ordering of the initializers.
1135 // Try (with -Wreorder)
1136 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001137 // template<class X> struct B : A<X> {
1138 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001139 // int x1;
1140 // };
1141 // B<int> x;
1142 // On seeing one dependent type, we should essentially exit this routine
1143 // while preserving user-declared initializer list. When this routine is
1144 // called during instantiatiation process, this routine will rebuild the
1145 // oderdered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001147 // If we have a dependent base initialization, we can't determine the
1148 // association between initializers and bases; just dump the known
1149 // initializers into the list, and don't try to deal with other bases.
1150 for (unsigned i = 0; i < NumInitializers; i++) {
1151 CXXBaseOrMemberInitializer *Member = Initializers[i];
1152 if (Member->isBaseInitializer())
1153 AllToInit.push_back(Member);
1154 }
1155 } else {
1156 // Push virtual bases before others.
1157 for (CXXRecordDecl::base_class_iterator VBase =
1158 ClassDecl->vbases_begin(),
1159 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1160 if (VBase->getType()->isDependentType())
1161 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001162 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001163 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001164 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001165 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1166 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1167 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1168 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001169 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001170 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001171 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001172 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001173 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1174 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001175 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
1176 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001177 Bases.push_back(VBase);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001178 else
1179 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1180
Mike Stump1eb44332009-09-09 15:08:12 +00001181 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001182 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001183 Ctor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001184 SourceLocation(),
1185 SourceLocation());
1186 AllToInit.push_back(Member);
1187 }
1188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001190 for (CXXRecordDecl::base_class_iterator Base =
1191 ClassDecl->bases_begin(),
1192 E = ClassDecl->bases_end(); Base != E; ++Base) {
1193 // Virtuals are in the virtual base list and already constructed.
1194 if (Base->isVirtual())
1195 continue;
1196 // Skip dependent types.
1197 if (Base->getType()->isDependentType())
1198 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001199 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001200 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001201 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001202 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1203 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1204 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1205 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001206 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001207 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001208 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001209 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001210 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001211 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001212 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1213 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001214 Bases.push_back(Base);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001215 else
1216 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1217
Mike Stump1eb44332009-09-09 15:08:12 +00001218 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001219 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1220 BaseDecl->getDefaultConstructor(Context),
1221 SourceLocation(),
1222 SourceLocation());
1223 AllToInit.push_back(Member);
1224 }
1225 }
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001228 // non-static data members.
1229 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1230 E = ClassDecl->field_end(); Field != E; ++Field) {
1231 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001232 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001233 Field->getType()->getAs<RecordType>()) {
1234 CXXRecordDecl *FieldClassDecl
1235 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001236 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001237 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1238 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1239 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1240 // set to the anonymous union data member used in the initializer
1241 // list.
1242 Value->setMember(*Field);
1243 Value->setAnonUnionMember(*FA);
1244 AllToInit.push_back(Value);
1245 break;
1246 }
1247 }
1248 }
1249 continue;
1250 }
1251 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001252 QualType FT = (*Field)->getType();
1253 if (const RecordType* RT = FT->getAs<RecordType>()) {
1254 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1255 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001256 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001257 FieldRecDecl->getDefaultConstructor(Context))
1258 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1259 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001260 AllToInit.push_back(Value);
1261 continue;
1262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001264 QualType FT = Context.getBaseElementType((*Field)->getType());
1265 if (const RecordType* RT = FT->getAs<RecordType>()) {
1266 CXXConstructorDecl *Ctor =
1267 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1268 if (!Ctor && !FT->isDependentType())
1269 Fields.push_back(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001270 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001271 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1272 Ctor,
1273 SourceLocation(),
1274 SourceLocation());
1275 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001276 if (Ctor)
1277 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001278 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1279 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1280 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1281 Diag((*Field)->getLocation(), diag::note_declared_at);
1282 }
1283 }
1284 else if (FT->isReferenceType()) {
1285 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1286 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1287 Diag((*Field)->getLocation(), diag::note_declared_at);
1288 }
1289 else if (FT.isConstQualified()) {
1290 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1291 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1292 Diag((*Field)->getLocation(), diag::note_declared_at);
1293 }
1294 }
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001296 NumInitializers = AllToInit.size();
1297 if (NumInitializers > 0) {
1298 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1299 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1300 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001302 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1303 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1304 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1305 }
1306}
1307
1308void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001309Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1310 CXXConstructorDecl *Constructor,
1311 CXXBaseOrMemberInitializer **Initializers,
1312 unsigned NumInitializers
1313 ) {
1314 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1315 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001316
1317 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001318 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001319 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001320 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001321 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1322 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001323 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001324 << 1 << Members[i]->getType();
1325}
1326
Eli Friedman6347f422009-07-21 19:28:10 +00001327static void *GetKeyForTopLevelField(FieldDecl *Field) {
1328 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001329 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001330 if (RT->getDecl()->isAnonymousStructOrUnion())
1331 return static_cast<void *>(RT->getDecl());
1332 }
1333 return static_cast<void *>(Field);
1334}
1335
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001336static void *GetKeyForBase(QualType BaseType) {
1337 if (const RecordType *RT = BaseType->getAs<RecordType>())
1338 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001340 assert(0 && "Unexpected base type!");
1341 return 0;
1342}
1343
Mike Stump1eb44332009-09-09 15:08:12 +00001344static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001345 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001346 // For fields injected into the class via declaration of an anonymous union,
1347 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001348 if (Member->isMemberInitializer()) {
1349 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001351 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001352 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001353 // in AnonUnionMember field.
1354 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1355 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001356 if (Field->getDeclContext()->isRecord()) {
1357 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1358 if (RD->isAnonymousStructOrUnion())
1359 return static_cast<void *>(RD);
1360 }
1361 return static_cast<void *>(Field);
1362 }
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001364 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001365}
1366
Mike Stump1eb44332009-09-09 15:08:12 +00001367void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001368 SourceLocation ColonLoc,
1369 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001370 if (!ConstructorDecl)
1371 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001372
1373 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001374
1375 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001376 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Anders Carlssona7b35212009-03-25 02:58:17 +00001378 if (!Constructor) {
1379 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1380 return;
1381 }
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001383 if (!Constructor->isDependentContext()) {
1384 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1385 bool err = false;
1386 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001387 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001388 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1389 void *KeyToMember = GetKeyForMember(Member);
1390 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1391 if (!PrevMember) {
1392 PrevMember = Member;
1393 continue;
1394 }
1395 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001396 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001397 diag::error_multiple_mem_initialization)
1398 << Field->getNameAsString();
1399 else {
1400 Type *BaseClass = Member->getBaseClass();
1401 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001402 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001403 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001404 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001405 }
1406 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1407 << 0;
1408 err = true;
1409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001411 if (err)
1412 return;
1413 }
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001415 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001416 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001417 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001419 if (Constructor->isDependentContext())
1420 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001421
1422 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001423 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001424 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001425 Diagnostic::Ignored)
1426 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001428 // Also issue warning if order of ctor-initializer list does not match order
1429 // of 1) base class declarations and 2) order of non-static data members.
1430 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001432 CXXRecordDecl *ClassDecl
1433 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1434 // Push virtual bases before others.
1435 for (CXXRecordDecl::base_class_iterator VBase =
1436 ClassDecl->vbases_begin(),
1437 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001438 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001440 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1441 E = ClassDecl->bases_end(); Base != E; ++Base) {
1442 // Virtuals are alread in the virtual base list and are constructed
1443 // first.
1444 if (Base->isVirtual())
1445 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001446 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001447 }
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001449 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1450 E = ClassDecl->field_end(); Field != E; ++Field)
1451 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001453 int Last = AllBaseOrMembers.size();
1454 int curIndex = 0;
1455 CXXBaseOrMemberInitializer *PrevMember = 0;
1456 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001457 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001458 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1459 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001460
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001461 for (; curIndex < Last; curIndex++)
1462 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1463 break;
1464 if (curIndex == Last) {
1465 assert(PrevMember && "Member not in member list?!");
1466 // Initializer as specified in ctor-initializer list is out of order.
1467 // Issue a warning diagnostic.
1468 if (PrevMember->isBaseInitializer()) {
1469 // Diagnostics is for an initialized base class.
1470 Type *BaseClass = PrevMember->getBaseClass();
1471 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001472 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001473 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001474 } else {
1475 FieldDecl *Field = PrevMember->getMember();
1476 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001477 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001478 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001479 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001480 // Also the note!
1481 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001482 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001483 diag::note_fieldorbase_initialized_here) << 0
1484 << Field->getNameAsString();
1485 else {
1486 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001487 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001488 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001489 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001490 }
1491 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001492 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001493 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001494 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001495 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001496 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001497}
1498
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001499void
1500Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1501 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1502 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001504 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1505 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1506 if (VBase->getType()->isDependentType())
1507 continue;
1508 // Skip over virtual bases which have trivial destructors.
1509 CXXRecordDecl *BaseClassDecl
1510 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1511 if (BaseClassDecl->hasTrivialDestructor())
1512 continue;
1513 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001514 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001515 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001516
1517 uintptr_t Member =
1518 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001519 | CXXDestructorDecl::VBASE;
1520 AllToDestruct.push_back(Member);
1521 }
1522 for (CXXRecordDecl::base_class_iterator Base =
1523 ClassDecl->bases_begin(),
1524 E = ClassDecl->bases_end(); Base != E; ++Base) {
1525 if (Base->isVirtual())
1526 continue;
1527 if (Base->getType()->isDependentType())
1528 continue;
1529 // Skip over virtual bases which have trivial destructors.
1530 CXXRecordDecl *BaseClassDecl
1531 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1532 if (BaseClassDecl->hasTrivialDestructor())
1533 continue;
1534 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001535 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001536 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001537 uintptr_t Member =
1538 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001539 | CXXDestructorDecl::DRCTNONVBASE;
1540 AllToDestruct.push_back(Member);
1541 }
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001543 // non-static data members.
1544 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1545 E = ClassDecl->field_end(); Field != E; ++Field) {
1546 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001548 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1549 // Skip over virtual bases which have trivial destructors.
1550 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1551 if (FieldClassDecl->hasTrivialDestructor())
1552 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001553 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001554 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001555 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001556 const_cast<CXXDestructorDecl*>(Dtor));
1557 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1558 AllToDestruct.push_back(Member);
1559 }
1560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001562 unsigned NumDestructions = AllToDestruct.size();
1563 if (NumDestructions > 0) {
1564 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001565 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001566 new (Context) uintptr_t [NumDestructions];
1567 // Insert in reverse order.
1568 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1569 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1570 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1571 }
1572}
1573
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001574void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001575 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001576 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001578 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
1580 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001581 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001582 BuildBaseOrMemberInitializers(Context,
1583 Constructor,
1584 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001585}
1586
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001587namespace {
1588 /// PureVirtualMethodCollector - traverses a class and its superclasses
1589 /// and determines if it has any pure virtual methods.
1590 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1591 ASTContext &Context;
1592
Sebastian Redldfe292d2009-03-22 21:28:55 +00001593 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001594 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001595
1596 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001597 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001599 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001601 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001602 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001603 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001605 MethodList List;
1606 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001608 // Copy the temporary list to methods, and make sure to ignore any
1609 // null entries.
1610 for (size_t i = 0, e = List.size(); i != e; ++i) {
1611 if (List[i])
1612 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001613 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001616 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001618 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1619 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001620 };
Mike Stump1eb44332009-09-09 15:08:12 +00001621
1622 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001623 MethodList& Methods) {
1624 // First, collect the pure virtual methods for the base classes.
1625 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1626 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001627 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001628 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001629 if (BaseDecl && BaseDecl->isAbstract())
1630 Collect(BaseDecl, Methods);
1631 }
1632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001634 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001635 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001637 MethodSetTy OverriddenMethods;
1638 size_t MethodsSize = Methods.size();
1639
Mike Stump1eb44332009-09-09 15:08:12 +00001640 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001641 i != e; ++i) {
1642 // Traverse the record, looking for methods.
1643 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001644 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001645 if (MD->isPure()) {
1646 Methods.push_back(MD);
1647 continue;
1648 }
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001650 // Otherwise, record all the overridden methods in our set.
1651 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1652 E = MD->end_overridden_methods(); I != E; ++I) {
1653 // Keep track of the overridden methods.
1654 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001655 }
1656 }
1657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
1659 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001660 // overridden.
1661 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1662 if (OverriddenMethods.count(Methods[i]))
1663 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001666 }
1667}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001668
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001669
Mike Stump1eb44332009-09-09 15:08:12 +00001670bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001671 unsigned DiagID, AbstractDiagSelID SelID,
1672 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001673 if (SelID == -1)
1674 return RequireNonAbstractType(Loc, T,
1675 PDiag(DiagID), CurrentRD);
1676 else
1677 return RequireNonAbstractType(Loc, T,
1678 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001679}
1680
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001681bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1682 const PartialDiagnostic &PD,
1683 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001684 if (!getLangOptions().CPlusPlus)
1685 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Anders Carlsson11f21a02009-03-23 19:10:31 +00001687 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001688 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001689 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Ted Kremenek6217b802009-07-29 21:53:49 +00001691 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001692 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001693 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001694 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001696 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001697 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Ted Kremenek6217b802009-07-29 21:53:49 +00001700 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001701 if (!RT)
1702 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001704 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1705 if (!RD)
1706 return false;
1707
Anders Carlssone65a3c82009-03-24 17:23:42 +00001708 if (CurrentRD && CurrentRD != RD)
1709 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001711 if (!RD->isAbstract())
1712 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001714 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001716 // Check if we've already emitted the list of pure virtual functions for this
1717 // class.
1718 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1719 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001721 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
1723 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001724 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1725 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001726
1727 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001728 MD->getDeclName();
1729 }
1730
1731 if (!PureVirtualClassDiagSet)
1732 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1733 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001735 return true;
1736}
1737
Anders Carlsson8211eff2009-03-24 01:19:16 +00001738namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001739 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001740 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1741 Sema &SemaRef;
1742 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Anders Carlssone65a3c82009-03-24 17:23:42 +00001744 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001745 bool Invalid = false;
1746
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001747 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1748 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001749 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001750
Anders Carlsson8211eff2009-03-24 01:19:16 +00001751 return Invalid;
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Anders Carlssone65a3c82009-03-24 17:23:42 +00001754 public:
1755 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1756 : SemaRef(SemaRef), AbstractClass(ac) {
1757 Visit(SemaRef.Context.getTranslationUnitDecl());
1758 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001759
Anders Carlssone65a3c82009-03-24 17:23:42 +00001760 bool VisitFunctionDecl(const FunctionDecl *FD) {
1761 if (FD->isThisDeclarationADefinition()) {
1762 // No need to do the check if we're in a definition, because it requires
1763 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001764 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001765 return VisitDeclContext(FD);
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlssone65a3c82009-03-24 17:23:42 +00001768 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001769 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001770 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001771 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1772 diag::err_abstract_type_in_decl,
1773 Sema::AbstractReturnType,
1774 AbstractClass);
1775
Mike Stump1eb44332009-09-09 15:08:12 +00001776 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001777 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001778 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001779 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001780 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001781 VD->getOriginalType(),
1782 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001783 Sema::AbstractParamType,
1784 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001785 }
1786
1787 return Invalid;
1788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Anders Carlssone65a3c82009-03-24 17:23:42 +00001790 bool VisitDecl(const Decl* D) {
1791 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1792 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Anders Carlssone65a3c82009-03-24 17:23:42 +00001794 return false;
1795 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001796 };
1797}
1798
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001799void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001800 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001801 SourceLocation LBrac,
1802 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001803 if (!TagDecl)
1804 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregor42af25f2009-05-11 19:58:34 +00001806 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001807 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001808 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001809 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001810
Chris Lattnerb28317a2009-03-28 19:18:32 +00001811 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001812 if (!RD->isAbstract()) {
1813 // Collect all the pure virtual methods and see if this is an abstract
1814 // class after all.
1815 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001816 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001817 RD->setAbstract(true);
1818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
1820 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001821 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Douglas Gregor42af25f2009-05-11 19:58:34 +00001823 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001824 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001825}
1826
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001827/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1828/// special functions, such as the default constructor, copy
1829/// constructor, or destructor, to the given C++ class (C++
1830/// [special]p1). This routine can only be executed just before the
1831/// definition of the class is complete.
1832void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001833 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001834 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001835
Sebastian Redl465226e2009-05-27 22:11:52 +00001836 // FIXME: Implicit declarations have exception specifications, which are
1837 // the union of the specifications of the implicitly called functions.
1838
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001839 if (!ClassDecl->hasUserDeclaredConstructor()) {
1840 // C++ [class.ctor]p5:
1841 // A default constructor for a class X is a constructor of class X
1842 // that can be called without an argument. If there is no
1843 // user-declared constructor for class X, a default constructor is
1844 // implicitly declared. An implicitly-declared default constructor
1845 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001846 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001847 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001848 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001849 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001850 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001851 Context.getFunctionType(Context.VoidTy,
1852 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001853 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001854 /*isExplicit=*/false,
1855 /*isInline=*/true,
1856 /*isImplicitlyDeclared=*/true);
1857 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001858 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001859 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001860 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001861 }
1862
1863 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1864 // C++ [class.copy]p4:
1865 // If the class definition does not explicitly declare a copy
1866 // constructor, one is declared implicitly.
1867
1868 // C++ [class.copy]p5:
1869 // The implicitly-declared copy constructor for a class X will
1870 // have the form
1871 //
1872 // X::X(const X&)
1873 //
1874 // if
1875 bool HasConstCopyConstructor = true;
1876
1877 // -- each direct or virtual base class B of X has a copy
1878 // constructor whose first parameter is of type const B& or
1879 // const volatile B&, and
1880 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1881 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1882 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001883 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001884 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001885 = BaseClassDecl->hasConstCopyConstructor(Context);
1886 }
1887
1888 // -- for all the nonstatic data members of X that are of a
1889 // class type M (or array thereof), each such class type
1890 // has a copy constructor whose first parameter is of type
1891 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001892 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1893 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001894 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001895 QualType FieldType = (*Field)->getType();
1896 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1897 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001898 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001899 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001900 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001901 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001902 = FieldClassDecl->hasConstCopyConstructor(Context);
1903 }
1904 }
1905
Sebastian Redl64b45f72009-01-05 20:52:13 +00001906 // Otherwise, the implicitly declared copy constructor will have
1907 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001908 //
1909 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001910 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001911 if (HasConstCopyConstructor)
1912 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001913 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001914
Sebastian Redl64b45f72009-01-05 20:52:13 +00001915 // An implicitly-declared copy constructor is an inline public
1916 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001917 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001918 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001919 CXXConstructorDecl *CopyConstructor
1920 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001921 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001922 Context.getFunctionType(Context.VoidTy,
1923 &ArgType, 1,
1924 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001925 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001926 /*isExplicit=*/false,
1927 /*isInline=*/true,
1928 /*isImplicitlyDeclared=*/true);
1929 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001930 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001931 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001932
1933 // Add the parameter to the constructor.
1934 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1935 ClassDecl->getLocation(),
1936 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001937 ArgType, /*DInfo=*/0,
1938 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001939 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001940 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001941 }
1942
Sebastian Redl64b45f72009-01-05 20:52:13 +00001943 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1944 // Note: The following rules are largely analoguous to the copy
1945 // constructor rules. Note that virtual bases are not taken into account
1946 // for determining the argument type of the operator. Note also that
1947 // operators taking an object instead of a reference are allowed.
1948 //
1949 // C++ [class.copy]p10:
1950 // If the class definition does not explicitly declare a copy
1951 // assignment operator, one is declared implicitly.
1952 // The implicitly-defined copy assignment operator for a class X
1953 // will have the form
1954 //
1955 // X& X::operator=(const X&)
1956 //
1957 // if
1958 bool HasConstCopyAssignment = true;
1959
1960 // -- each direct base class B of X has a copy assignment operator
1961 // whose parameter is of type const B&, const volatile B& or B,
1962 // and
1963 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1964 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1965 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001966 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001967 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001968 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001969 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001970 }
1971
1972 // -- for all the nonstatic data members of X that are of a class
1973 // type M (or array thereof), each such class type has a copy
1974 // assignment operator whose parameter is of type const M&,
1975 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001976 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1977 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001978 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001979 QualType FieldType = (*Field)->getType();
1980 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1981 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001982 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001983 const CXXRecordDecl *FieldClassDecl
1984 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001985 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001986 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001987 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001988 }
1989 }
1990
1991 // Otherwise, the implicitly declared copy assignment operator will
1992 // have the form
1993 //
1994 // X& X::operator=(X&)
1995 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001996 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001997 if (HasConstCopyAssignment)
1998 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001999 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002000
2001 // An implicitly-declared copy assignment operator is an inline public
2002 // member of its class.
2003 DeclarationName Name =
2004 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2005 CXXMethodDecl *CopyAssignment =
2006 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2007 Context.getFunctionType(RetType, &ArgType, 1,
2008 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002009 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002010 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002011 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002012 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002013 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002014
2015 // Add the parameter to the operator.
2016 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2017 ClassDecl->getLocation(),
2018 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002019 ArgType, /*DInfo=*/0,
2020 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002021 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002022
2023 // Don't call addedAssignmentOperator. There is no way to distinguish an
2024 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002025 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002026 }
2027
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002028 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002029 // C++ [class.dtor]p2:
2030 // If a class has no user-declared destructor, a destructor is
2031 // declared implicitly. An implicitly-declared destructor is an
2032 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002033 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002034 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002035 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002036 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002037 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002038 Context.getFunctionType(Context.VoidTy,
2039 0, 0, false, 0),
2040 /*isInline=*/true,
2041 /*isImplicitlyDeclared=*/true);
2042 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002043 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002044 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002045 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002046 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002047}
2048
Douglas Gregor6569d682009-05-27 23:11:45 +00002049void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002050 Decl *D = TemplateD.getAs<Decl>();
2051 if (!D)
2052 return;
2053
2054 TemplateParameterList *Params = 0;
2055 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2056 Params = Template->getTemplateParameters();
2057 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2058 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2059 Params = PartialSpec->getTemplateParameters();
2060 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002061 return;
2062
Douglas Gregor6569d682009-05-27 23:11:45 +00002063 for (TemplateParameterList::iterator Param = Params->begin(),
2064 ParamEnd = Params->end();
2065 Param != ParamEnd; ++Param) {
2066 NamedDecl *Named = cast<NamedDecl>(*Param);
2067 if (Named->getDeclName()) {
2068 S->AddDecl(DeclPtrTy::make(Named));
2069 IdResolver.AddDecl(Named);
2070 }
2071 }
2072}
2073
Douglas Gregor72b505b2008-12-16 21:30:33 +00002074/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2075/// parsing a top-level (non-nested) C++ class, and we are now
2076/// parsing those parts of the given Method declaration that could
2077/// not be parsed earlier (C++ [class.mem]p2), such as default
2078/// arguments. This action should enter the scope of the given
2079/// Method declaration as if we had just parsed the qualified method
2080/// name. However, it should not bring the parameters into scope;
2081/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002082void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002083 if (!MethodD)
2084 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002086 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregor72b505b2008-12-16 21:30:33 +00002088 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002089 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002090 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002091 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2092 SS.setScopeRep(
2093 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002094 ActOnCXXEnterDeclaratorScope(S, SS);
2095}
2096
2097/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2098/// C++ method declaration. We're (re-)introducing the given
2099/// function parameter into scope for use in parsing later parts of
2100/// the method declaration. For example, we could see an
2101/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002102void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002103 if (!ParamD)
2104 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Chris Lattnerb28317a2009-03-28 19:18:32 +00002106 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002107
2108 // If this parameter has an unparsed default argument, clear it out
2109 // to make way for the parsed default argument.
2110 if (Param->hasUnparsedDefaultArg())
2111 Param->setDefaultArg(0);
2112
Chris Lattnerb28317a2009-03-28 19:18:32 +00002113 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002114 if (Param->getDeclName())
2115 IdResolver.AddDecl(Param);
2116}
2117
2118/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2119/// processing the delayed method declaration for Method. The method
2120/// declaration is now considered finished. There may be a separate
2121/// ActOnStartOfFunctionDef action later (not necessarily
2122/// immediately!) for this method, if it was also defined inside the
2123/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002124void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002125 if (!MethodD)
2126 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002128 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Chris Lattnerb28317a2009-03-28 19:18:32 +00002130 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002131 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002132 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002133 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2134 SS.setScopeRep(
2135 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002136 ActOnCXXExitDeclaratorScope(S, SS);
2137
2138 // Now that we have our default arguments, check the constructor
2139 // again. It could produce additional diagnostics or affect whether
2140 // the class has implicitly-declared destructors, among other
2141 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002142 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2143 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002144
2145 // Check the default arguments, which we may have added.
2146 if (!Method->isInvalidDecl())
2147 CheckCXXDefaultArguments(Method);
2148}
2149
Douglas Gregor42a552f2008-11-05 20:51:48 +00002150/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002151/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002152/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002153/// emit diagnostics and set the invalid bit to true. In any case, the type
2154/// will be updated to reflect a well-formed type for the constructor and
2155/// returned.
2156QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2157 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002158 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002159
2160 // C++ [class.ctor]p3:
2161 // A constructor shall not be virtual (10.3) or static (9.4). A
2162 // constructor can be invoked for a const, volatile or const
2163 // volatile object. A constructor shall not be declared const,
2164 // volatile, or const volatile (9.3.2).
2165 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002166 if (!D.isInvalidType())
2167 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2168 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2169 << SourceRange(D.getIdentifierLoc());
2170 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002171 }
2172 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002173 if (!D.isInvalidType())
2174 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2175 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2176 << SourceRange(D.getIdentifierLoc());
2177 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002178 SC = FunctionDecl::None;
2179 }
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Chris Lattner65401802009-04-25 08:28:21 +00002181 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2182 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002183 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002184 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2185 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002186 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002187 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2188 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002189 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002190 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2191 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002192 }
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregor42a552f2008-11-05 20:51:48 +00002194 // Rebuild the function type "R" without any type qualifiers (in
2195 // case any of the errors above fired) and with "void" as the
2196 // return type, since constructors don't have return types. We
2197 // *always* have to do this, because GetTypeForDeclarator will
2198 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002199 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002200 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2201 Proto->getNumArgs(),
2202 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002203}
2204
Douglas Gregor72b505b2008-12-16 21:30:33 +00002205/// CheckConstructor - Checks a fully-formed constructor for
2206/// well-formedness, issuing any diagnostics required. Returns true if
2207/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002208void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002209 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002210 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2211 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002212 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002213
2214 // C++ [class.copy]p3:
2215 // A declaration of a constructor for a class X is ill-formed if
2216 // its first parameter is of type (optionally cv-qualified) X and
2217 // either there are no other parameters or else all other
2218 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002219 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002220 ((Constructor->getNumParams() == 1) ||
2221 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002222 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002223 QualType ParamType = Constructor->getParamDecl(0)->getType();
2224 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2225 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002226 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2227 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002228 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002229 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002230 }
2231 }
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Douglas Gregor72b505b2008-12-16 21:30:33 +00002233 // Notify the class that we've added a constructor.
2234 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002235}
2236
Mike Stump1eb44332009-09-09 15:08:12 +00002237static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002238FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2239 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2240 FTI.ArgInfo[0].Param &&
2241 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2242}
2243
Douglas Gregor42a552f2008-11-05 20:51:48 +00002244/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2245/// the well-formednes of the destructor declarator @p D with type @p
2246/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002247/// emit diagnostics and set the declarator to invalid. Even if this happens,
2248/// will be updated to reflect a well-formed type for the destructor and
2249/// returned.
2250QualType Sema::CheckDestructorDeclarator(Declarator &D,
2251 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002252 // C++ [class.dtor]p1:
2253 // [...] A typedef-name that names a class is a class-name
2254 // (7.1.3); however, a typedef-name that names a class shall not
2255 // be used as the identifier in the declarator for a destructor
2256 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002257 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00002258 if (isa<TypedefType>(DeclaratorType)) {
2259 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002260 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002261 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002262 }
2263
2264 // C++ [class.dtor]p2:
2265 // A destructor is used to destroy objects of its class type. A
2266 // destructor takes no parameters, and no return type can be
2267 // specified for it (not even void). The address of a destructor
2268 // shall not be taken. A destructor shall not be static. A
2269 // destructor can be invoked for a const, volatile or const
2270 // volatile object. A destructor shall not be declared const,
2271 // volatile or const volatile (9.3.2).
2272 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002273 if (!D.isInvalidType())
2274 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2275 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2276 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002277 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002278 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002279 }
Chris Lattner65401802009-04-25 08:28:21 +00002280 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002281 // Destructors don't have return types, but the parser will
2282 // happily parse something like:
2283 //
2284 // class X {
2285 // float ~X();
2286 // };
2287 //
2288 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002289 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2290 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2291 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Chris Lattner65401802009-04-25 08:28:21 +00002294 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2295 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002296 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002297 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2298 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002299 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002300 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2301 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002302 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002303 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2304 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002305 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002306 }
2307
2308 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002309 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002310 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2311
2312 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002313 FTI.freeArgs();
2314 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002315 }
2316
Mike Stump1eb44332009-09-09 15:08:12 +00002317 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002318 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002319 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002320 D.setInvalidType();
2321 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002322
2323 // Rebuild the function type "R" without any type qualifiers or
2324 // parameters (in case any of the errors above fired) and with
2325 // "void" as the return type, since destructors don't have return
2326 // types. We *always* have to do this, because GetTypeForDeclarator
2327 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002328 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002329}
2330
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002331/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2332/// well-formednes of the conversion function declarator @p D with
2333/// type @p R. If there are any errors in the declarator, this routine
2334/// will emit diagnostics and return true. Otherwise, it will return
2335/// false. Either way, the type @p R will be updated to reflect a
2336/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002337void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002338 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002339 // C++ [class.conv.fct]p1:
2340 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002341 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002342 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002343 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002344 if (!D.isInvalidType())
2345 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2346 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2347 << SourceRange(D.getIdentifierLoc());
2348 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002349 SC = FunctionDecl::None;
2350 }
Chris Lattner6e475012009-04-25 08:35:12 +00002351 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002352 // Conversion functions don't have return types, but the parser will
2353 // happily parse something like:
2354 //
2355 // class X {
2356 // float operator bool();
2357 // };
2358 //
2359 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002360 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2361 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2362 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002363 }
2364
2365 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002366 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002367 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2368
2369 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002370 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002371 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002372 }
2373
Mike Stump1eb44332009-09-09 15:08:12 +00002374 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002375 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002376 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002377 D.setInvalidType();
2378 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002379
2380 // C++ [class.conv.fct]p4:
2381 // The conversion-type-id shall not represent a function type nor
2382 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002383 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002384 if (ConvType->isArrayType()) {
2385 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2386 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002387 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002388 } else if (ConvType->isFunctionType()) {
2389 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2390 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002391 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002392 }
2393
2394 // Rebuild the function type "R" without any parameters (in case any
2395 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002396 // return type.
2397 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002398 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002399
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002400 // C++0x explicit conversion operators.
2401 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002402 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002403 diag::warn_explicit_conversion_functions)
2404 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002405}
2406
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002407/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2408/// the declaration of the given C++ conversion function. This routine
2409/// is responsible for recording the conversion function in the C++
2410/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002411Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002412 assert(Conversion && "Expected to receive a conversion function declaration");
2413
Douglas Gregor9d350972008-12-12 08:25:50 +00002414 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002415
2416 // Make sure we aren't redeclaring the conversion function.
2417 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002418
2419 // C++ [class.conv.fct]p1:
2420 // [...] A conversion function is never used to convert a
2421 // (possibly cv-qualified) object to the (possibly cv-qualified)
2422 // same object type (or a reference to it), to a (possibly
2423 // cv-qualified) base class of that type (or a reference to it),
2424 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002425 // FIXME: Suppress this warning if the conversion function ends up being a
2426 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002427 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002428 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002429 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002430 ConvType = ConvTypeRef->getPointeeType();
2431 if (ConvType->isRecordType()) {
2432 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2433 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002434 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002435 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002436 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002437 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002438 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002439 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002440 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002441 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002442 }
2443
Douglas Gregor70316a02008-12-26 15:00:45 +00002444 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002445 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002446 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002447 = Conversion->getDescribedFunctionTemplate())
2448 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002449 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002450 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002451 Conv = Conversions->function_begin(),
2452 ConvEnd = Conversions->function_end();
2453 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002454 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002455 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002456 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002457 }
2458 }
2459 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002460 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002461 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002462 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002463 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002464 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002465
Chris Lattnerb28317a2009-03-28 19:18:32 +00002466 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002467}
2468
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002469//===----------------------------------------------------------------------===//
2470// Namespace Handling
2471//===----------------------------------------------------------------------===//
2472
2473/// ActOnStartNamespaceDef - This is called at the start of a namespace
2474/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002475Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2476 SourceLocation IdentLoc,
2477 IdentifierInfo *II,
2478 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002479 NamespaceDecl *Namespc =
2480 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2481 Namespc->setLBracLoc(LBrace);
2482
2483 Scope *DeclRegionScope = NamespcScope->getParent();
2484
2485 if (II) {
2486 // C++ [namespace.def]p2:
2487 // The identifier in an original-namespace-definition shall not have been
2488 // previously defined in the declarative region in which the
2489 // original-namespace-definition appears. The identifier in an
2490 // original-namespace-definition is the name of the namespace. Subsequently
2491 // in that declarative region, it is treated as an original-namespace-name.
2492
John McCallf36e02d2009-10-09 21:13:30 +00002493 NamedDecl *PrevDecl
2494 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Douglas Gregor44b43212008-12-11 16:49:14 +00002496 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2497 // This is an extended namespace definition.
2498 // Attach this namespace decl to the chain of extended namespace
2499 // definitions.
2500 OrigNS->setNextNamespace(Namespc);
2501 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002502
Mike Stump1eb44332009-09-09 15:08:12 +00002503 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002504 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002505 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002506 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002507 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002508 } else if (PrevDecl) {
2509 // This is an invalid name redefinition.
2510 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2511 << Namespc->getDeclName();
2512 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2513 Namespc->setInvalidDecl();
2514 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002515 } else if (II->isStr("std") &&
2516 CurContext->getLookupContext()->isTranslationUnit()) {
2517 // This is the first "real" definition of the namespace "std", so update
2518 // our cache of the "std" namespace to point at this definition.
2519 if (StdNamespace) {
2520 // We had already defined a dummy namespace "std". Link this new
2521 // namespace definition to the dummy namespace "std".
2522 StdNamespace->setNextNamespace(Namespc);
2523 StdNamespace->setLocation(IdentLoc);
2524 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2525 }
2526
2527 // Make our StdNamespace cache point at the first real definition of the
2528 // "std" namespace.
2529 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002530 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002531
2532 PushOnScopeChains(Namespc, DeclRegionScope);
2533 } else {
John McCall9aeed322009-10-01 00:25:31 +00002534 // Anonymous namespaces.
2535
2536 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2537 // behaves as if it were replaced by
2538 // namespace unique { /* empty body */ }
2539 // using namespace unique;
2540 // namespace unique { namespace-body }
2541 // where all occurrences of 'unique' in a translation unit are
2542 // replaced by the same identifier and this identifier differs
2543 // from all other identifiers in the entire program.
2544
2545 // We just create the namespace with an empty name and then add an
2546 // implicit using declaration, just like the standard suggests.
2547 //
2548 // CodeGen enforces the "universally unique" aspect by giving all
2549 // declarations semantically contained within an anonymous
2550 // namespace internal linkage.
2551
2552 assert(Namespc->isAnonymousNamespace());
2553 CurContext->addDecl(Namespc);
2554
2555 UsingDirectiveDecl* UD
2556 = UsingDirectiveDecl::Create(Context, CurContext,
2557 /* 'using' */ LBrace,
2558 /* 'namespace' */ SourceLocation(),
2559 /* qualifier */ SourceRange(),
2560 /* NNS */ NULL,
2561 /* identifier */ SourceLocation(),
2562 Namespc,
2563 /* Ancestor */ CurContext);
2564 UD->setImplicit();
2565 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002566 }
2567
2568 // Although we could have an invalid decl (i.e. the namespace name is a
2569 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002570 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2571 // for the namespace has the declarations that showed up in that particular
2572 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002573 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002574 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002575}
2576
2577/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2578/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002579void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2580 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002581 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2582 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2583 Namespc->setRBracLoc(RBrace);
2584 PopDeclContext();
2585}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002586
Chris Lattnerb28317a2009-03-28 19:18:32 +00002587Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2588 SourceLocation UsingLoc,
2589 SourceLocation NamespcLoc,
2590 const CXXScopeSpec &SS,
2591 SourceLocation IdentLoc,
2592 IdentifierInfo *NamespcName,
2593 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002594 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2595 assert(NamespcName && "Invalid NamespcName.");
2596 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002597 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002598
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002599 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002600
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002601 // Lookup namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002602 LookupResult R;
2603 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002604 if (R.isAmbiguous()) {
2605 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002606 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002607 }
John McCallf36e02d2009-10-09 21:13:30 +00002608 if (!R.empty()) {
2609 NamedDecl *NS = R.getFoundDecl();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002610 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002611 // C++ [namespace.udir]p1:
2612 // A using-directive specifies that the names in the nominated
2613 // namespace can be used in the scope in which the
2614 // using-directive appears after the using-directive. During
2615 // unqualified name lookup (3.4.1), the names appear as if they
2616 // were declared in the nearest enclosing namespace which
2617 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002618 // namespace. [Note: in this context, "contains" means "contains
2619 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002620
2621 // Find enclosing context containing both using-directive and
2622 // nominated namespace.
2623 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2624 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2625 CommonAncestor = CommonAncestor->getParent();
2626
Mike Stump1eb44332009-09-09 15:08:12 +00002627 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002628 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002629 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002630 SS.getRange(),
2631 (NestedNameSpecifier *)SS.getScopeRep(),
2632 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002633 cast<NamespaceDecl>(NS),
2634 CommonAncestor);
2635 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002636 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002637 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002638 }
2639
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002640 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002641 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002642 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002643}
2644
2645void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2646 // If scope has associated entity, then using directive is at namespace
2647 // or translation unit scope. We add UsingDirectiveDecls, into
2648 // it's lookup structure.
2649 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002650 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002651 else
2652 // Otherwise it is block-sope. using-directives will affect lookup
2653 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002654 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002655}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002656
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002657
2658Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002659 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002660 SourceLocation UsingLoc,
2661 const CXXScopeSpec &SS,
2662 SourceLocation IdentLoc,
2663 IdentifierInfo *TargetName,
2664 OverloadedOperatorKind Op,
2665 AttributeList *AttrList,
2666 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002667 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002668 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002670 DeclarationName Name;
2671 if (TargetName)
2672 Name = TargetName;
2673 else
2674 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
2676 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002677 Name, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002678 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002679 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002680 UD->setAccess(AS);
2681 }
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Anders Carlssonc72160b2009-08-28 05:40:36 +00002683 return DeclPtrTy::make(UD);
2684}
2685
2686NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2687 const CXXScopeSpec &SS,
2688 SourceLocation IdentLoc,
2689 DeclarationName Name,
2690 AttributeList *AttrList,
2691 bool IsTypeName) {
2692 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2693 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002694
Anders Carlsson550b14b2009-08-28 05:49:21 +00002695 // FIXME: We ignore attributes for now.
2696 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002698 if (SS.isEmpty()) {
2699 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002700 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002701 }
Mike Stump1eb44332009-09-09 15:08:12 +00002702
2703 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002704 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2705
Anders Carlsson550b14b2009-08-28 05:49:21 +00002706 if (isUnknownSpecialization(SS)) {
2707 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2708 SS.getRange(), NNS,
2709 IdentLoc, Name, IsTypeName);
2710 }
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002712 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002714 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2715 // C++0x N2914 [namespace.udecl]p3:
2716 // A using-declaration used as a member-declaration shall refer to a member
2717 // of a base class of the class being defined, shall refer to a member of an
2718 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002719 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002720 // a member of a base class of the class being defined.
2721 const Type *Ty = NNS->getAsType();
2722 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2723 Diag(SS.getRange().getBegin(),
2724 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2725 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002726 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002727 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002728
2729 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2730 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002731 } else {
2732 // C++0x N2914 [namespace.udecl]p8:
2733 // A using-declaration for a class member shall be a member-declaration.
2734 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002735 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002736 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002737 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002738 }
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002740 // C++0x N2914 [namespace.udecl]p9:
2741 // In a using-declaration, a prefix :: refers to the global namespace.
2742 if (NNS->getKind() == NestedNameSpecifier::Global)
2743 LookupContext = Context.getTranslationUnitDecl();
2744 else
2745 LookupContext = NNS->getAsNamespace();
2746 }
2747
2748
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002749 // Lookup target name.
John McCallf36e02d2009-10-09 21:13:30 +00002750 LookupResult R;
2751 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002752
John McCallf36e02d2009-10-09 21:13:30 +00002753 if (R.empty()) {
Anders Carlsson05180af2009-08-30 00:58:45 +00002754 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlssonc72160b2009-08-28 05:40:36 +00002755 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002756 }
2757
John McCallf36e02d2009-10-09 21:13:30 +00002758 // FIXME: handle ambiguity?
2759 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002761 if (IsTypeName && !isa<TypeDecl>(ND)) {
2762 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002763 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002764 }
2765
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002766 // C++0x N2914 [namespace.udecl]p6:
2767 // A using-declaration shall not name a namespace.
2768 if (isa<NamespaceDecl>(ND)) {
2769 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2770 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002771 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002772 }
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Anders Carlssonc72160b2009-08-28 05:40:36 +00002774 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2775 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002776}
2777
Anders Carlsson81c85c42009-03-28 23:53:49 +00002778/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2779/// is a namespace alias, returns the namespace it points to.
2780static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2781 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2782 return AD->getNamespace();
2783 return dyn_cast_or_null<NamespaceDecl>(D);
2784}
2785
Mike Stump1eb44332009-09-09 15:08:12 +00002786Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002787 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002788 SourceLocation AliasLoc,
2789 IdentifierInfo *Alias,
2790 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002791 SourceLocation IdentLoc,
2792 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Anders Carlsson81c85c42009-03-28 23:53:49 +00002794 // Lookup the namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002795 LookupResult R;
2796 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlsson81c85c42009-03-28 23:53:49 +00002797
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002798 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002799 if (NamedDecl *PrevDecl
2800 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002801 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002802 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002803 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00002804 if (!R.isAmbiguous() && !R.empty() &&
2805 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00002806 return DeclPtrTy();
2807 }
Mike Stump1eb44332009-09-09 15:08:12 +00002808
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002809 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2810 diag::err_redefinition_different_kind;
2811 Diag(AliasLoc, DiagID) << Alias;
2812 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002813 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002814 }
2815
Anders Carlsson5721c682009-03-28 06:42:02 +00002816 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002817 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002818 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002819 }
Mike Stump1eb44332009-09-09 15:08:12 +00002820
John McCallf36e02d2009-10-09 21:13:30 +00002821 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00002822 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002823 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002824 }
Mike Stump1eb44332009-09-09 15:08:12 +00002825
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002826 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002827 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2828 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002829 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00002830 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002832 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002833 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002834}
2835
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002836void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2837 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002838 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2839 !Constructor->isUsed()) &&
2840 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002842 CXXRecordDecl *ClassDecl
2843 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002844 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002845 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002846 // implicitly defined, all the implicitly-declared default constructors
2847 // for its base class and its non-static data members shall have been
2848 // implicitly defined.
2849 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002850 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2851 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002852 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002853 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002854 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002855 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002856 BaseClassDecl->getDefaultConstructor(Context))
2857 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002858 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002859 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002860 << Context.getTagDeclType(ClassDecl) << 0
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002861 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002862 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002863 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002864 err = true;
2865 }
2866 }
2867 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002868 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2869 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002870 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2871 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2872 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002873 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002874 CXXRecordDecl *FieldClassDecl
2875 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002876 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002877 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002878 FieldClassDecl->getDefaultConstructor(Context))
2879 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002880 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002881 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002882 << Context.getTagDeclType(ClassDecl) << 1 <<
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002883 Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002884 Diag((*Field)->getLocation(), diag::note_field_decl);
Mike Stump1eb44332009-09-09 15:08:12 +00002885 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002886 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002887 err = true;
2888 }
2889 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002890 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002891 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002892 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002893 Diag((*Field)->getLocation(), diag::note_declared_at);
2894 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002895 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002896 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002897 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002898 Diag((*Field)->getLocation(), diag::note_declared_at);
2899 err = true;
2900 }
2901 }
2902 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002903 Constructor->setUsed();
2904 else
2905 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002906}
2907
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002908void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002909 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002910 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2911 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002912
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002913 CXXRecordDecl *ClassDecl
2914 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2915 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2916 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00002917 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002918 // implicitly defined, all the implicitly-declared default destructors
2919 // for its base class and its non-static data members shall have been
2920 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002921 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2922 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002923 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002924 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002925 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002926 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002927 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2928 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2929 else
Mike Stump1eb44332009-09-09 15:08:12 +00002930 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002931 "DefineImplicitDestructor - missing dtor in a base class");
2932 }
2933 }
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002935 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2936 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002937 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2938 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2939 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002940 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002941 CXXRecordDecl *FieldClassDecl
2942 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2943 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002944 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002945 const_cast<CXXDestructorDecl*>(
2946 FieldClassDecl->getDestructor(Context)))
2947 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2948 else
Mike Stump1eb44332009-09-09 15:08:12 +00002949 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002950 "DefineImplicitDestructor - missing dtor in class of a data member");
2951 }
2952 }
2953 }
2954 Destructor->setUsed();
2955}
2956
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002957void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2958 CXXMethodDecl *MethodDecl) {
2959 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2960 MethodDecl->getOverloadedOperator() == OO_Equal &&
2961 !MethodDecl->isUsed()) &&
2962 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002964 CXXRecordDecl *ClassDecl
2965 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002967 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002968 // Before the implicitly-declared copy assignment operator for a class is
2969 // implicitly defined, all implicitly-declared copy assignment operators
2970 // for its direct base classes and its nonstatic data members shall have
2971 // been implicitly defined.
2972 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002973 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2974 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002975 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002976 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002977 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002978 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2979 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2980 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002981 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2982 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002983 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2984 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2985 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002986 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002987 CXXRecordDecl *FieldClassDecl
2988 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002989 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002990 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2991 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002992 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002993 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002994 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2995 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002996 Diag(CurrentLocation, diag::note_first_required_here);
2997 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002998 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002999 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003000 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3001 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003002 Diag(CurrentLocation, diag::note_first_required_here);
3003 err = true;
3004 }
3005 }
3006 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003007 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003008}
3009
3010CXXMethodDecl *
3011Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3012 CXXRecordDecl *ClassDecl) {
3013 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3014 QualType RHSType(LHSType);
3015 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003016 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003017 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003018 RHSType = Context.getCVRQualifiedType(RHSType,
3019 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003020 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3021 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003022 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003023 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3024 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003025 SourceLocation()));
3026 Expr *Args[2] = { &*LHS, &*RHS };
3027 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003028 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003029 CandidateSet);
3030 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003031 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003032 ClassDecl->getLocation(), Best) == OR_Success)
3033 return cast<CXXMethodDecl>(Best->Function);
3034 assert(false &&
3035 "getAssignOperatorMethod - copy assignment operator method not found");
3036 return 0;
3037}
3038
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003039void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3040 CXXConstructorDecl *CopyConstructor,
3041 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003042 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003043 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3044 !CopyConstructor->isUsed()) &&
3045 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003047 CXXRecordDecl *ClassDecl
3048 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3049 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003050 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003051 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003052 // implicitly defined, all the implicitly-declared copy constructors
3053 // for its base class and its non-static data members shall have been
3054 // implicitly defined.
3055 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3056 Base != ClassDecl->bases_end(); ++Base) {
3057 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003058 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003059 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003060 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003061 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003062 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003063 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3064 FieldEnd = ClassDecl->field_end();
3065 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003066 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3067 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3068 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003069 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003070 CXXRecordDecl *FieldClassDecl
3071 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003072 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003073 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003074 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003075 }
3076 }
3077 CopyConstructor->setUsed();
3078}
3079
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003080Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003081Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003082 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003083 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003084 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Douglas Gregor39da0b82009-09-09 23:08:42 +00003086 // C++ [class.copy]p15:
3087 // Whenever a temporary class object is copied using a copy constructor, and
3088 // this object and the copy have the same cv-unqualified type, an
3089 // implementation is permitted to treat the original and the copy as two
3090 // different ways of referring to the same object and not perform a copy at
3091 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003093 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003094 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003095 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003096 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3097 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003098 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3099 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3100 E = ICE->getSubExpr();
3101
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003102 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3103 Elidable = true;
3104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105
3106 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003107 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003108}
3109
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003110/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3111/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003112Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003113Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3114 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003115 MultiExprArg ExprArgs) {
3116 unsigned NumExprs = ExprArgs.size();
3117 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003118
Douglas Gregor39da0b82009-09-09 23:08:42 +00003119 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3120 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003121}
3122
Anders Carlssone7624a72009-08-27 05:08:22 +00003123Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003124Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3125 QualType Ty,
3126 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003127 MultiExprArg Args,
3128 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003129 unsigned NumExprs = Args.size();
3130 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregor39da0b82009-09-09 23:08:42 +00003132 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3133 TyBeginLoc, Exprs,
3134 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003135}
3136
3137
Mike Stump1eb44332009-09-09 15:08:12 +00003138bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003139 CXXConstructorDecl *Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00003140 QualType DeclInitType,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003141 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003142 OwningExprResult TempResult =
3143 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003144 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003145 if (TempResult.isInvalid())
3146 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003148 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003149 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003150 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003151 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Anders Carlssonfe2de492009-08-25 05:18:00 +00003153 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003154}
3155
Mike Stump1eb44332009-09-09 15:08:12 +00003156void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003157 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003158 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003159 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003160 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003161 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003162 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003163}
3164
Mike Stump1eb44332009-09-09 15:08:12 +00003165/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003166/// ActOnDeclarator, when a C++ direct initializer is present.
3167/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003168void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3169 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003170 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003171 SourceLocation *CommaLocs,
3172 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003173 unsigned NumExprs = Exprs.size();
3174 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003175 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003176
3177 // If there is no declaration, there was an error parsing it. Just ignore
3178 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003179 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003180 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003182 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3183 if (!VDecl) {
3184 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3185 RealDecl->setInvalidDecl();
3186 return;
3187 }
3188
Douglas Gregor83ddad32009-08-26 21:14:46 +00003189 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003190 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003191 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3192 //
3193 // Clients that want to distinguish between the two forms, can check for
3194 // direct initializer using VarDecl::hasCXXDirectInitializer().
3195 // A major benefit is that clients that don't particularly care about which
3196 // exactly form was it (like the CodeGen) can handle both cases without
3197 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003198
Douglas Gregor83ddad32009-08-26 21:14:46 +00003199 // If either the declaration has a dependent type or if any of the expressions
3200 // is type-dependent, we represent the initialization via a ParenListExpr for
3201 // later use during template instantiation.
3202 if (VDecl->getType()->isDependentType() ||
3203 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3204 // Let clients know that initialization was done with a direct initializer.
3205 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Douglas Gregor83ddad32009-08-26 21:14:46 +00003207 // Store the initialization expressions as a ParenListExpr.
3208 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003209 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003210 new (Context) ParenListExpr(Context, LParenLoc,
3211 (Expr **)Exprs.release(),
3212 NumExprs, RParenLoc));
3213 return;
3214 }
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Douglas Gregor83ddad32009-08-26 21:14:46 +00003216
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003217 // C++ 8.5p11:
3218 // The form of initialization (using parentheses or '=') is generally
3219 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003220 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003221 QualType DeclInitType = VDecl->getType();
3222 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3223 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003224
Douglas Gregor615c5d42009-03-24 16:43:20 +00003225 // FIXME: This isn't the right place to complete the type.
3226 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3227 diag::err_typecheck_decl_incomplete_type)) {
3228 VDecl->setInvalidDecl();
3229 return;
3230 }
3231
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003232 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003233 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3234
Douglas Gregor18fe5682008-11-03 20:45:27 +00003235 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003236 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003237 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003238 VDecl->getLocation(),
3239 SourceRange(VDecl->getLocation(),
3240 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003241 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003242 IK_Direct,
3243 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003244 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003245 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003246 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003247 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003248 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003249 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003250 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003251 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003252 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003253 return;
3254 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003255
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003256 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003257 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3258 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003259 RealDecl->setInvalidDecl();
3260 return;
3261 }
3262
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003263 // Let clients know that initialization was done with a direct initializer.
3264 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003265
3266 assert(NumExprs == 1 && "Expected 1 expression");
3267 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003268 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3269 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003270}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003271
Douglas Gregor39da0b82009-09-09 23:08:42 +00003272/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3273/// may occur as part of direct-initialization or copy-initialization.
3274///
3275/// \param ClassType the type of the object being initialized, which must have
3276/// class type.
3277///
3278/// \param ArgsPtr the arguments provided to initialize the object
3279///
3280/// \param Loc the source location where the initialization occurs
3281///
3282/// \param Range the source range that covers the entire initialization
3283///
3284/// \param InitEntity the name of the entity being initialized, if known
3285///
3286/// \param Kind the type of initialization being performed
3287///
3288/// \param ConvertedArgs a vector that will be filled in with the
3289/// appropriately-converted arguments to the constructor (if initialization
3290/// succeeded).
3291///
3292/// \returns the constructor used to initialize the object, if successful.
3293/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003294CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003295Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003296 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003297 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003298 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003299 InitializationKind Kind,
3300 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003301 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003302 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003303 Expr **Args = (Expr **)ArgsPtr.get();
3304 unsigned NumArgs = ArgsPtr.size();
3305
Mike Stump1eb44332009-09-09 15:08:12 +00003306 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003307 // If the initialization is direct-initialization, or if it is
3308 // copy-initialization where the cv-unqualified version of the
3309 // source type is the same class as, or a derived class of, the
3310 // class of the destination, constructors are considered. The
3311 // applicable constructors are enumerated (13.3.1.3), and the
3312 // best one is chosen through overload resolution (13.3). The
3313 // constructor so selected is called to initialize the object,
3314 // with the initializer expression(s) as its argument(s). If no
3315 // constructor applies, or the overload resolution is ambiguous,
3316 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003317 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3318 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003319
3320 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003321 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003322 = Context.DeclarationNames.getCXXConstructorName(
3323 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003324 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003325 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003326 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003327 // Find the constructor (which may be a template).
3328 CXXConstructorDecl *Constructor = 0;
3329 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3330 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003331 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003332 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3333 else
3334 Constructor = cast<CXXConstructorDecl>(*Con);
3335
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003336 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003337 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003338 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003339 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3340 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003341 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003342 Args, NumArgs, CandidateSet);
3343 else
3344 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3345 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003346 }
3347
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003348 // FIXME: When we decide not to synthesize the implicitly-declared
3349 // constructors, we'll need to make them appear here.
3350
Douglas Gregor18fe5682008-11-03 20:45:27 +00003351 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003352 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003353 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003354 // We found a constructor. Break out so that we can convert the arguments
3355 // appropriately.
3356 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Douglas Gregor18fe5682008-11-03 20:45:27 +00003358 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003359 if (InitEntity)
3360 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003361 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003362 else
3363 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003364 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003365 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003366 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Douglas Gregor18fe5682008-11-03 20:45:27 +00003368 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003369 if (InitEntity)
3370 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3371 else
3372 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003373 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3374 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003375
3376 case OR_Deleted:
3377 if (InitEntity)
3378 Diag(Loc, diag::err_ovl_deleted_init)
3379 << Best->Function->isDeleted()
3380 << InitEntity << Range;
3381 else
3382 Diag(Loc, diag::err_ovl_deleted_init)
3383 << Best->Function->isDeleted()
3384 << InitEntity << Range;
3385 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3386 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Douglas Gregor39da0b82009-09-09 23:08:42 +00003389 // Convert the arguments, fill in default arguments, etc.
3390 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3391 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3392 return 0;
3393
3394 return Constructor;
3395}
3396
3397/// \brief Given a constructor and the set of arguments provided for the
3398/// constructor, convert the arguments and add any required default arguments
3399/// to form a proper call to this constructor.
3400///
3401/// \returns true if an error occurred, false otherwise.
3402bool
3403Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3404 MultiExprArg ArgsPtr,
3405 SourceLocation Loc,
3406 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3407 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3408 unsigned NumArgs = ArgsPtr.size();
3409 Expr **Args = (Expr **)ArgsPtr.get();
3410
3411 const FunctionProtoType *Proto
3412 = Constructor->getType()->getAs<FunctionProtoType>();
3413 assert(Proto && "Constructor without a prototype?");
3414 unsigned NumArgsInProto = Proto->getNumArgs();
3415 unsigned NumArgsToCheck = NumArgs;
3416
3417 // If too few arguments are available, we'll fill in the rest with defaults.
3418 if (NumArgs < NumArgsInProto) {
3419 NumArgsToCheck = NumArgsInProto;
3420 ConvertedArgs.reserve(NumArgsInProto);
3421 } else {
3422 ConvertedArgs.reserve(NumArgs);
3423 if (NumArgs > NumArgsInProto)
3424 NumArgsToCheck = NumArgsInProto;
3425 }
3426
3427 // Convert arguments
3428 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3429 QualType ProtoArgType = Proto->getArgType(i);
3430
3431 Expr *Arg;
3432 if (i < NumArgs) {
3433 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003434
3435 // Pass the argument.
3436 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3437 return true;
3438
3439 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003440 } else {
3441 ParmVarDecl *Param = Constructor->getParamDecl(i);
3442
3443 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3444 if (DefArg.isInvalid())
3445 return true;
3446
3447 Arg = DefArg.takeAs<Expr>();
3448 }
3449
3450 ConvertedArgs.push_back(Arg);
3451 }
3452
3453 // If this is a variadic call, handle args passed through "...".
3454 if (Proto->isVariadic()) {
3455 // Promote the arguments (C99 6.5.2.2p7).
3456 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3457 Expr *Arg = Args[i];
3458 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3459 return true;
3460
3461 ConvertedArgs.push_back(Arg);
3462 Args[i] = 0;
3463 }
3464 }
3465
3466 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003467}
3468
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003469/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3470/// determine whether they are reference-related,
3471/// reference-compatible, reference-compatible with added
3472/// qualification, or incompatible, for use in C++ initialization by
3473/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3474/// type, and the first type (T1) is the pointee type of the reference
3475/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003476Sema::ReferenceCompareResult
3477Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003478 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003479 assert(!T1->isReferenceType() &&
3480 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003481 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3482
3483 T1 = Context.getCanonicalType(T1);
3484 T2 = Context.getCanonicalType(T2);
3485 QualType UnqualT1 = T1.getUnqualifiedType();
3486 QualType UnqualT2 = T2.getUnqualifiedType();
3487
3488 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003489 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003490 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003491 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003492 if (UnqualT1 == UnqualT2)
3493 DerivedToBase = false;
3494 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3495 DerivedToBase = true;
3496 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003497 return Ref_Incompatible;
3498
3499 // At this point, we know that T1 and T2 are reference-related (at
3500 // least).
3501
3502 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003503 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003504 // reference-related to T2 and cv1 is the same cv-qualification
3505 // as, or greater cv-qualification than, cv2. For purposes of
3506 // overload resolution, cases for which cv1 is greater
3507 // cv-qualification than cv2 are identified as
3508 // reference-compatible with added qualification (see 13.3.3.2).
3509 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3510 return Ref_Compatible;
3511 else if (T1.isMoreQualifiedThan(T2))
3512 return Ref_Compatible_With_Added_Qualification;
3513 else
3514 return Ref_Related;
3515}
3516
3517/// CheckReferenceInit - Check the initialization of a reference
3518/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3519/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003520/// list), and DeclType is the type of the declaration. When ICS is
3521/// non-null, this routine will compute the implicit conversion
3522/// sequence according to C++ [over.ics.ref] and will not produce any
3523/// diagnostics; when ICS is null, it will emit diagnostics when any
3524/// errors are found. Either way, a return value of true indicates
3525/// that there was a failure, a return value of false indicates that
3526/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003527///
3528/// When @p SuppressUserConversions, user-defined conversions are
3529/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003530/// When @p AllowExplicit, we also permit explicit user-defined
3531/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003532/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003533bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003534Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003535 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003536 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003537 bool AllowExplicit, bool ForceRValue,
3538 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003539 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3540
Ted Kremenek6217b802009-07-29 21:53:49 +00003541 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003542 QualType T2 = Init->getType();
3543
Douglas Gregor904eed32008-11-10 20:40:00 +00003544 // If the initializer is the address of an overloaded function, try
3545 // to resolve the overloaded function. If all goes well, T2 is the
3546 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003547 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003548 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003549 ICS != 0);
3550 if (Fn) {
3551 // Since we're performing this reference-initialization for
3552 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003553 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003554 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003555 return true;
3556
Douglas Gregor904eed32008-11-10 20:40:00 +00003557 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003558 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003559
3560 T2 = Fn->getType();
3561 }
3562 }
3563
Douglas Gregor15da57e2008-10-29 02:00:59 +00003564 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003565 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003566 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003567 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3568 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003569 ReferenceCompareResult RefRelationship
Douglas Gregor15da57e2008-10-29 02:00:59 +00003570 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3571
3572 // Most paths end in a failed conversion.
3573 if (ICS)
3574 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003575
3576 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003577 // A reference to type "cv1 T1" is initialized by an expression
3578 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003579
3580 // -- If the initializer expression
3581
Sebastian Redla9845802009-03-29 15:27:50 +00003582 // Rvalue references cannot bind to lvalues (N2812).
3583 // There is absolutely no situation where they can. In particular, note that
3584 // this is ill-formed, even if B has a user-defined conversion to A&&:
3585 // B b;
3586 // A&& r = b;
3587 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3588 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003589 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003590 << Init->getSourceRange();
3591 return true;
3592 }
3593
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003594 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003595 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3596 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003597 //
3598 // Note that the bit-field check is skipped if we are just computing
3599 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003600 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003601 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003602 BindsDirectly = true;
3603
Douglas Gregor15da57e2008-10-29 02:00:59 +00003604 if (ICS) {
3605 // C++ [over.ics.ref]p1:
3606 // When a parameter of reference type binds directly (8.5.3)
3607 // to an argument expression, the implicit conversion sequence
3608 // is the identity conversion, unless the argument expression
3609 // has a type that is a derived class of the parameter type,
3610 // in which case the implicit conversion sequence is a
3611 // derived-to-base Conversion (13.3.3.1).
3612 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3613 ICS->Standard.First = ICK_Identity;
3614 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3615 ICS->Standard.Third = ICK_Identity;
3616 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3617 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003618 ICS->Standard.ReferenceBinding = true;
3619 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003620 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003621 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003622
3623 // Nothing more to do: the inaccessibility/ambiguity check for
3624 // derived-to-base conversions is suppressed when we're
3625 // computing the implicit conversion sequence (C++
3626 // [over.best.ics]p2).
3627 return false;
3628 } else {
3629 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003630 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3631 if (DerivedToBase)
3632 CK = CastExpr::CK_DerivedToBase;
3633 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003634 }
3635 }
3636
3637 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003638 // implicitly converted to an lvalue of type "cv3 T3,"
3639 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003640 // 92) (this conversion is selected by enumerating the
3641 // applicable conversion functions (13.3.1.6) and choosing
3642 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003643 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3644 !RequireCompleteType(SourceLocation(), T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003645 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003646 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003647
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003648 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003649 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003650 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003651 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003652 = Conversions->function_begin();
3653 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003654 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003655 = dyn_cast<FunctionTemplateDecl>(*Func);
3656 CXXConversionDecl *Conv;
3657 if (ConvTemplate)
3658 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3659 else
3660 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003661
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003662 // If the conversion function doesn't return a reference type,
3663 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003664 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003665 (AllowExplicit || !Conv->isExplicit())) {
3666 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003667 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003668 CandidateSet);
3669 else
3670 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3671 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003672 }
3673
3674 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003675 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003676 case OR_Success:
3677 // This is a direct binding.
3678 BindsDirectly = true;
3679
3680 if (ICS) {
3681 // C++ [over.ics.ref]p1:
3682 //
3683 // [...] If the parameter binds directly to the result of
3684 // applying a conversion function to the argument
3685 // expression, the implicit conversion sequence is a
3686 // user-defined conversion sequence (13.3.3.1.2), with the
3687 // second standard conversion sequence either an identity
3688 // conversion or, if the conversion function returns an
3689 // entity of a type that is a derived class of the parameter
3690 // type, a derived-to-base Conversion.
3691 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3692 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3693 ICS->UserDefined.After = Best->FinalConversion;
3694 ICS->UserDefined.ConversionFunction = Best->Function;
3695 assert(ICS->UserDefined.After.ReferenceBinding &&
3696 ICS->UserDefined.After.DirectBinding &&
3697 "Expected a direct reference binding!");
3698 return false;
3699 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003700 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003701 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003702 CastExpr::CK_UserDefinedConversion,
3703 cast<CXXMethodDecl>(Best->Function),
3704 Owned(Init));
3705 Init = InitConversion.takeAs<Expr>();
3706
3707 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3708 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003709 }
3710 break;
3711
3712 case OR_Ambiguous:
3713 assert(false && "Ambiguous reference binding conversions not implemented.");
3714 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003716 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003717 case OR_Deleted:
3718 // There was no suitable conversion, or we found a deleted
3719 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003720 break;
3721 }
3722 }
Mike Stump1eb44332009-09-09 15:08:12 +00003723
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003724 if (BindsDirectly) {
3725 // C++ [dcl.init.ref]p4:
3726 // [...] In all cases where the reference-related or
3727 // reference-compatible relationship of two types is used to
3728 // establish the validity of a reference binding, and T1 is a
3729 // base class of T2, a program that necessitates such a binding
3730 // is ill-formed if T1 is an inaccessible (clause 11) or
3731 // ambiguous (10.2) base class of T2.
3732 //
3733 // Note that we only check this condition when we're allowed to
3734 // complain about errors, because we should not be checking for
3735 // ambiguity (or inaccessibility) unless the reference binding
3736 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003737 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003738 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003739 Init->getSourceRange());
3740 else
3741 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003742 }
3743
3744 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003745 // type (i.e., cv1 shall be const), or the reference shall be an
3746 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003747 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003748 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003749 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003750 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3751 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003752 return true;
3753 }
3754
3755 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003756 // class type, and "cv1 T1" is reference-compatible with
3757 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003758 // following ways (the choice is implementation-defined):
3759 //
3760 // -- The reference is bound to the object represented by
3761 // the rvalue (see 3.10) or to a sub-object within that
3762 // object.
3763 //
Eli Friedman33a31382009-08-05 19:21:58 +00003764 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003765 // a constructor is called to copy the entire rvalue
3766 // object into the temporary. The reference is bound to
3767 // the temporary or to a sub-object within the
3768 // temporary.
3769 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003770 // The constructor that would be used to make the copy
3771 // shall be callable whether or not the copy is actually
3772 // done.
3773 //
Sebastian Redla9845802009-03-29 15:27:50 +00003774 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003775 // freedom, so we will always take the first option and never build
3776 // a temporary in this case. FIXME: We will, however, have to check
3777 // for the presence of a copy constructor in C++98/03 mode.
3778 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003779 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3780 if (ICS) {
3781 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3782 ICS->Standard.First = ICK_Identity;
3783 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3784 ICS->Standard.Third = ICK_Identity;
3785 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3786 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003787 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003788 ICS->Standard.DirectBinding = false;
3789 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003790 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003791 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003792 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3793 if (DerivedToBase)
3794 CK = CastExpr::CK_DerivedToBase;
3795 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003796 }
3797 return false;
3798 }
3799
Eli Friedman33a31382009-08-05 19:21:58 +00003800 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003801 // initialized from the initializer expression using the
3802 // rules for a non-reference copy initialization (8.5). The
3803 // reference is then bound to the temporary. If T1 is
3804 // reference-related to T2, cv1 must be the same
3805 // cv-qualification as, or greater cv-qualification than,
3806 // cv2; otherwise, the program is ill-formed.
3807 if (RefRelationship == Ref_Related) {
3808 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3809 // we would be reference-compatible or reference-compatible with
3810 // added qualification. But that wasn't the case, so the reference
3811 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003812 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003813 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003814 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3815 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003816 return true;
3817 }
3818
Douglas Gregor734d9862009-01-30 23:27:23 +00003819 // If at least one of the types is a class type, the types are not
3820 // related, and we aren't allowed any user conversions, the
3821 // reference binding fails. This case is important for breaking
3822 // recursion, since TryImplicitConversion below will attempt to
3823 // create a temporary through the use of a copy constructor.
3824 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3825 (T1->isRecordType() || T2->isRecordType())) {
3826 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003827 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00003828 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3829 return true;
3830 }
3831
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003832 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003833 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003834 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003835 //
Sebastian Redla9845802009-03-29 15:27:50 +00003836 // When a parameter of reference type is not bound directly to
3837 // an argument expression, the conversion sequence is the one
3838 // required to convert the argument expression to the
3839 // underlying type of the reference according to
3840 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3841 // to copy-initializing a temporary of the underlying type with
3842 // the argument expression. Any difference in top-level
3843 // cv-qualification is subsumed by the initialization itself
3844 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003845 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3846 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003847 /*ForceRValue=*/false,
3848 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Sebastian Redla9845802009-03-29 15:27:50 +00003850 // Of course, that's still a reference binding.
3851 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3852 ICS->Standard.ReferenceBinding = true;
3853 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003854 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003855 ImplicitConversionSequence::UserDefinedConversion) {
3856 ICS->UserDefined.After.ReferenceBinding = true;
3857 ICS->UserDefined.After.RRefBinding = isRValRef;
3858 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003859 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3860 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003861 ImplicitConversionSequence Conversions;
3862 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3863 false, false,
3864 Conversions);
3865 if (badConversion) {
3866 if ((Conversions.ConversionKind ==
3867 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00003868 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00003869 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003870 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3871 for (int j = Conversions.ConversionFunctionSet.size()-1;
3872 j >= 0; j--) {
3873 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3874 Diag(Func->getLocation(), diag::err_ovl_candidate);
3875 }
3876 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00003877 else {
3878 if (isRValRef)
3879 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3880 << Init->getSourceRange();
3881 else
3882 Diag(DeclLoc, diag::err_invalid_initialization)
3883 << DeclType << Init->getType() << Init->getSourceRange();
3884 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003885 }
3886 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003887 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003888}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003889
3890/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3891/// of this overloaded operator is well-formed. If so, returns false;
3892/// otherwise, emits appropriate diagnostics and returns true.
3893bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003894 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003895 "Expected an overloaded operator declaration");
3896
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003897 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3898
Mike Stump1eb44332009-09-09 15:08:12 +00003899 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003900 // The allocation and deallocation functions, operator new,
3901 // operator new[], operator delete and operator delete[], are
3902 // described completely in 3.7.3. The attributes and restrictions
3903 // found in the rest of this subclause do not apply to them unless
3904 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003905 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003906 if (Op == OO_New || Op == OO_Array_New ||
3907 Op == OO_Delete || Op == OO_Array_Delete)
3908 return false;
3909
3910 // C++ [over.oper]p6:
3911 // An operator function shall either be a non-static member
3912 // function or be a non-member function and have at least one
3913 // parameter whose type is a class, a reference to a class, an
3914 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003915 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3916 if (MethodDecl->isStatic())
3917 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003918 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003919 } else {
3920 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003921 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3922 ParamEnd = FnDecl->param_end();
3923 Param != ParamEnd; ++Param) {
3924 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003925 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3926 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003927 ClassOrEnumParam = true;
3928 break;
3929 }
3930 }
3931
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003932 if (!ClassOrEnumParam)
3933 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003934 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003935 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003936 }
3937
3938 // C++ [over.oper]p8:
3939 // An operator function cannot have default arguments (8.3.6),
3940 // except where explicitly stated below.
3941 //
Mike Stump1eb44332009-09-09 15:08:12 +00003942 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003943 // (C++ [over.call]p1).
3944 if (Op != OO_Call) {
3945 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3946 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003947 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00003948 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00003949 diag::err_operator_overload_default_arg)
3950 << FnDecl->getDeclName();
3951 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003952 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003953 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003954 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003955 }
3956 }
3957
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003958 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3959 { false, false, false }
3960#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3961 , { Unary, Binary, MemberOnly }
3962#include "clang/Basic/OperatorKinds.def"
3963 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003964
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003965 bool CanBeUnaryOperator = OperatorUses[Op][0];
3966 bool CanBeBinaryOperator = OperatorUses[Op][1];
3967 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003968
3969 // C++ [over.oper]p8:
3970 // [...] Operator functions cannot have more or fewer parameters
3971 // than the number required for the corresponding operator, as
3972 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00003973 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003974 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003975 if (Op != OO_Call &&
3976 ((NumParams == 1 && !CanBeUnaryOperator) ||
3977 (NumParams == 2 && !CanBeBinaryOperator) ||
3978 (NumParams < 1) || (NumParams > 2))) {
3979 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003980 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003981 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003982 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003983 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003984 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003985 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003986 assert(CanBeBinaryOperator &&
3987 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003988 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003989 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003990
Chris Lattner416e46f2008-11-21 07:57:12 +00003991 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003992 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003993 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003994
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003995 // Overloaded operators other than operator() cannot be variadic.
3996 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00003997 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003998 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003999 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004000 }
4001
4002 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004003 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4004 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004005 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004006 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004007 }
4008
4009 // C++ [over.inc]p1:
4010 // The user-defined function called operator++ implements the
4011 // prefix and postfix ++ operator. If this function is a member
4012 // function with no parameters, or a non-member function with one
4013 // parameter of class or enumeration type, it defines the prefix
4014 // increment operator ++ for objects of that type. If the function
4015 // is a member function with one parameter (which shall be of type
4016 // int) or a non-member function with two parameters (the second
4017 // of which shall be of type int), it defines the postfix
4018 // increment operator ++ for objects of that type.
4019 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4020 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4021 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004022 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004023 ParamIsInt = BT->getKind() == BuiltinType::Int;
4024
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004025 if (!ParamIsInt)
4026 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004027 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004028 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004029 }
4030
Sebastian Redl64b45f72009-01-05 20:52:13 +00004031 // Notify the class if it got an assignment operator.
4032 if (Op == OO_Equal) {
4033 // Would have returned earlier otherwise.
4034 assert(isa<CXXMethodDecl>(FnDecl) &&
4035 "Overloaded = not member, but not filtered.");
4036 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00004037 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004038 Method->getParent()->addedAssignmentOperator(Context, Method);
4039 }
4040
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004041 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004042}
Chris Lattner5a003a42008-12-17 07:09:26 +00004043
Douglas Gregor074149e2009-01-05 19:45:36 +00004044/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4045/// linkage specification, including the language and (if present)
4046/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4047/// the location of the language string literal, which is provided
4048/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4049/// the '{' brace. Otherwise, this linkage specification does not
4050/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004051Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4052 SourceLocation ExternLoc,
4053 SourceLocation LangLoc,
4054 const char *Lang,
4055 unsigned StrSize,
4056 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004057 LinkageSpecDecl::LanguageIDs Language;
4058 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4059 Language = LinkageSpecDecl::lang_c;
4060 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4061 Language = LinkageSpecDecl::lang_cxx;
4062 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004063 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004064 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004065 }
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Chris Lattnercc98eac2008-12-17 07:13:27 +00004067 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004068
Douglas Gregor074149e2009-01-05 19:45:36 +00004069 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004070 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004071 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004072 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004073 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004074 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004075}
4076
Douglas Gregor074149e2009-01-05 19:45:36 +00004077/// ActOnFinishLinkageSpecification - Completely the definition of
4078/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4079/// valid, it's the position of the closing '}' brace in a linkage
4080/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004081Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4082 DeclPtrTy LinkageSpec,
4083 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004084 if (LinkageSpec)
4085 PopDeclContext();
4086 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004087}
4088
Douglas Gregord308e622009-05-18 20:51:54 +00004089/// \brief Perform semantic analysis for the variable declaration that
4090/// occurs within a C++ catch clause, returning the newly-created
4091/// variable.
4092VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004093 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004094 IdentifierInfo *Name,
4095 SourceLocation Loc,
4096 SourceRange Range) {
4097 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004098
4099 // Arrays and functions decay.
4100 if (ExDeclType->isArrayType())
4101 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4102 else if (ExDeclType->isFunctionType())
4103 ExDeclType = Context.getPointerType(ExDeclType);
4104
4105 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4106 // The exception-declaration shall not denote a pointer or reference to an
4107 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004108 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004109 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004110 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004111 Invalid = true;
4112 }
Douglas Gregord308e622009-05-18 20:51:54 +00004113
Sebastian Redl4b07b292008-12-22 19:15:10 +00004114 QualType BaseType = ExDeclType;
4115 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004116 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004117 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004118 BaseType = Ptr->getPointeeType();
4119 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004120 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004121 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004122 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004123 BaseType = Ref->getPointeeType();
4124 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004125 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004126 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004127 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004128 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004129 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004130
Mike Stump1eb44332009-09-09 15:08:12 +00004131 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004132 RequireNonAbstractType(Loc, ExDeclType,
4133 diag::err_abstract_type_in_decl,
4134 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004135 Invalid = true;
4136
Douglas Gregord308e622009-05-18 20:51:54 +00004137 // FIXME: Need to test for ability to copy-construct and destroy the
4138 // exception variable.
4139
Sebastian Redl8351da02008-12-22 21:35:02 +00004140 // FIXME: Need to check for abstract classes.
4141
Mike Stump1eb44332009-09-09 15:08:12 +00004142 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004143 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004144
4145 if (Invalid)
4146 ExDecl->setInvalidDecl();
4147
4148 return ExDecl;
4149}
4150
4151/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4152/// handler.
4153Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004154 DeclaratorInfo *DInfo = 0;
4155 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004156
4157 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004158 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004159 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004160 // The scope should be freshly made just for us. There is just no way
4161 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004162 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004163 if (PrevDecl->isTemplateParameter()) {
4164 // Maybe we will complain about the shadowed template parameter.
4165 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004166 }
4167 }
4168
Chris Lattnereaaebc72009-04-25 08:06:05 +00004169 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004170 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4171 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004172 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004173 }
4174
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004175 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004176 D.getIdentifier(),
4177 D.getIdentifierLoc(),
4178 D.getDeclSpec().getSourceRange());
4179
Chris Lattnereaaebc72009-04-25 08:06:05 +00004180 if (Invalid)
4181 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Sebastian Redl4b07b292008-12-22 19:15:10 +00004183 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004184 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004185 PushOnScopeChains(ExDecl, S);
4186 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004187 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004188
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004189 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004190 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004191}
Anders Carlssonfb311762009-03-14 00:25:26 +00004192
Mike Stump1eb44332009-09-09 15:08:12 +00004193Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004194 ExprArg assertexpr,
4195 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004196 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004197 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004198 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4199
Anders Carlssonc3082412009-03-14 00:33:21 +00004200 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4201 llvm::APSInt Value(32);
4202 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4203 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4204 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004205 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004206 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004207
Anders Carlssonc3082412009-03-14 00:33:21 +00004208 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004209 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004210 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004211 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004212 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004213 }
4214 }
Mike Stump1eb44332009-09-09 15:08:12 +00004215
Anders Carlsson77d81422009-03-15 17:35:16 +00004216 assertexpr.release();
4217 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004218 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004219 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004220
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004221 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004222 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004223}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004224
John McCalldd4a3b02009-09-16 22:47:08 +00004225/// Handle a friend type declaration. This works in tandem with
4226/// ActOnTag.
4227///
4228/// Notes on friend class templates:
4229///
4230/// We generally treat friend class declarations as if they were
4231/// declaring a class. So, for example, the elaborated type specifier
4232/// in a friend declaration is required to obey the restrictions of a
4233/// class-head (i.e. no typedefs in the scope chain), template
4234/// parameters are required to match up with simple template-ids, &c.
4235/// However, unlike when declaring a template specialization, it's
4236/// okay to refer to a template specialization without an empty
4237/// template parameter declaration, e.g.
4238/// friend class A<T>::B<unsigned>;
4239/// We permit this as a special case; if there are any template
4240/// parameters present at all, require proper matching, i.e.
4241/// template <> template <class T> friend class A<int>::B;
John McCall02cace72009-08-28 07:59:38 +00004242Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
John McCall05b23ea2009-09-14 21:59:20 +00004243 const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004244 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004245 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004246
4247 assert(DS.isFriendSpecified());
4248 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4249
John McCalldd4a3b02009-09-16 22:47:08 +00004250 // Try to convert the decl specifier to a type. This works for
4251 // friend templates because ActOnTag never produces a ClassTemplateDecl
4252 // for a TUK_Friend.
John McCall6b2becf2009-09-08 17:47:29 +00004253 bool invalid = false;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00004254 QualType SourceTy;
4255 QualType T = ConvertDeclSpecToType(DS, Loc, invalid, SourceTy);
John McCall6b2becf2009-09-08 17:47:29 +00004256 if (invalid) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004257
John McCalldd4a3b02009-09-16 22:47:08 +00004258 // This is definitely an error in C++98. It's probably meant to
4259 // be forbidden in C++0x, too, but the specification is just
4260 // poorly written.
4261 //
4262 // The problem is with declarations like the following:
4263 // template <T> friend A<T>::foo;
4264 // where deciding whether a class C is a friend or not now hinges
4265 // on whether there exists an instantiation of A that causes
4266 // 'foo' to equal C. There are restrictions on class-heads
4267 // (which we declare (by fiat) elaborated friend declarations to
4268 // be) that makes this tractable.
4269 //
4270 // FIXME: handle "template <> friend class A<T>;", which
4271 // is possibly well-formed? Who even knows?
4272 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4273 Diag(Loc, diag::err_tagless_friend_type_template)
4274 << DS.getSourceRange();
4275 return DeclPtrTy();
4276 }
4277
John McCall02cace72009-08-28 07:59:38 +00004278 // C++ [class.friend]p2:
4279 // An elaborated-type-specifier shall be used in a friend declaration
4280 // for a class.*
4281 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004282 // This is one of the rare places in Clang where it's legitimate to
4283 // ask about the "spelling" of the type.
4284 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4285 // If we evaluated the type to a record type, suggest putting
4286 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004287 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004288 RecordDecl *RD = RT->getDecl();
4289
4290 std::string InsertionText = std::string(" ") + RD->getKindName();
4291
John McCalle3af0232009-10-07 23:34:25 +00004292 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4293 << (unsigned) RD->getTagKind()
4294 << T
4295 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004296 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4297 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004298 return DeclPtrTy();
4299 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004300 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4301 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004302 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004303 }
4304 }
4305
John McCalle3af0232009-10-07 23:34:25 +00004306 // Enum types cannot be friends.
4307 if (T->getAs<EnumType>()) {
4308 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4309 << SourceRange(DS.getFriendSpecLoc());
4310 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004311 }
John McCall02cace72009-08-28 07:59:38 +00004312
John McCall02cace72009-08-28 07:59:38 +00004313 // C++98 [class.friend]p1: A friend of a class is a function
4314 // or class that is not a member of the class . . .
4315 // But that's a silly restriction which nobody implements for
4316 // inner classes, and C++0x removes it anyway, so we only report
4317 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004318 if (!getLangOptions().CPlusPlus0x)
4319 if (const RecordType *RT = T->getAs<RecordType>())
4320 if (RT->getDecl()->getDeclContext() == CurContext)
4321 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004322
John McCalldd4a3b02009-09-16 22:47:08 +00004323 Decl *D;
4324 if (TempParams.size())
4325 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4326 TempParams.size(),
4327 (TemplateParameterList**) TempParams.release(),
4328 T.getTypePtr(),
4329 DS.getFriendSpecLoc());
4330 else
4331 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4332 DS.getFriendSpecLoc());
4333 D->setAccess(AS_public);
4334 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004335
John McCalldd4a3b02009-09-16 22:47:08 +00004336 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004337}
4338
John McCallbbbcdd92009-09-11 21:02:39 +00004339Sema::DeclPtrTy
4340Sema::ActOnFriendFunctionDecl(Scope *S,
4341 Declarator &D,
4342 bool IsDefinition,
4343 MultiTemplateParamsArg TemplateParams) {
4344 // FIXME: do something with template parameters
4345
John McCall02cace72009-08-28 07:59:38 +00004346 const DeclSpec &DS = D.getDeclSpec();
4347
4348 assert(DS.isFriendSpecified());
4349 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4350
4351 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004352 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004353 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004354
4355 // C++ [class.friend]p1
4356 // A friend of a class is a function or class....
4357 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004358 // It *doesn't* see through dependent types, which is correct
4359 // according to [temp.arg.type]p3:
4360 // If a declaration acquires a function type through a
4361 // type dependent on a template-parameter and this causes
4362 // a declaration that does not use the syntactic form of a
4363 // function declarator to have a function type, the program
4364 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004365 if (!T->isFunctionType()) {
4366 Diag(Loc, diag::err_unexpected_friend);
4367
4368 // It might be worthwhile to try to recover by creating an
4369 // appropriate declaration.
4370 return DeclPtrTy();
4371 }
4372
4373 // C++ [namespace.memdef]p3
4374 // - If a friend declaration in a non-local class first declares a
4375 // class or function, the friend class or function is a member
4376 // of the innermost enclosing namespace.
4377 // - The name of the friend is not found by simple name lookup
4378 // until a matching declaration is provided in that namespace
4379 // scope (either before or after the class declaration granting
4380 // friendship).
4381 // - If a friend function is called, its name may be found by the
4382 // name lookup that considers functions from namespaces and
4383 // classes associated with the types of the function arguments.
4384 // - When looking for a prior declaration of a class or a function
4385 // declared as a friend, scopes outside the innermost enclosing
4386 // namespace scope are not considered.
4387
John McCall02cace72009-08-28 07:59:38 +00004388 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4389 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004390 assert(Name);
4391
John McCall67d1a672009-08-06 02:15:43 +00004392 // The context we found the declaration in, or in which we should
4393 // create the declaration.
4394 DeclContext *DC;
4395
4396 // FIXME: handle local classes
4397
4398 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004399 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004400 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4401 DC = computeDeclContext(ScopeQual);
4402
4403 // FIXME: handle dependent contexts
4404 if (!DC) return DeclPtrTy();
4405
John McCallf36e02d2009-10-09 21:13:30 +00004406 LookupResult R;
4407 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4408 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004409
4410 // If searching in that context implicitly found a declaration in
4411 // a different context, treat it like it wasn't found at all.
4412 // TODO: better diagnostics for this case. Suggesting the right
4413 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004414 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004415 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004416 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4417 return DeclPtrTy();
4418 }
4419
4420 // C++ [class.friend]p1: A friend of a class is a function or
4421 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004422 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004423 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4424
John McCall67d1a672009-08-06 02:15:43 +00004425 // Otherwise walk out to the nearest namespace scope looking for matches.
4426 } else {
4427 // TODO: handle local class contexts.
4428
4429 DC = CurContext;
4430 while (true) {
4431 // Skip class contexts. If someone can cite chapter and verse
4432 // for this behavior, that would be nice --- it's what GCC and
4433 // EDG do, and it seems like a reasonable intent, but the spec
4434 // really only says that checks for unqualified existing
4435 // declarations should stop at the nearest enclosing namespace,
4436 // not that they should only consider the nearest enclosing
4437 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004438 while (DC->isRecord())
4439 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004440
John McCallf36e02d2009-10-09 21:13:30 +00004441 LookupResult R;
4442 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4443 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004444
4445 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004446 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004447 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004448
John McCall67d1a672009-08-06 02:15:43 +00004449 if (DC->isFileContext()) break;
4450 DC = DC->getParent();
4451 }
4452
4453 // C++ [class.friend]p1: A friend of a class is a function or
4454 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004455 // C++0x changes this for both friend types and functions.
4456 // Most C++ 98 compilers do seem to give an error here, so
4457 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004458 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004459 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4460 }
4461
Douglas Gregor182ddf02009-09-28 00:08:27 +00004462 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004463 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00004464 if (D.getKind() == Declarator::DK_Constructor ||
4465 D.getKind() == Declarator::DK_Destructor ||
4466 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00004467 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00004468 (D.getKind() == Declarator::DK_Constructor ? 0 :
4469 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004470 return DeclPtrTy();
4471 }
John McCall67d1a672009-08-06 02:15:43 +00004472 }
4473
Douglas Gregor182ddf02009-09-28 00:08:27 +00004474 bool Redeclaration = false;
4475 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
John McCall3f9a8a62009-08-11 06:59:38 +00004476 MultiTemplateParamsArg(*this),
4477 IsDefinition,
4478 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004479 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004480
Douglas Gregor182ddf02009-09-28 00:08:27 +00004481 assert(ND->getDeclContext() == DC);
4482 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004483
John McCallab88d972009-08-31 22:39:49 +00004484 // Add the function declaration to the appropriate lookup tables,
4485 // adjusting the redeclarations list as necessary. We don't
4486 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004487 //
John McCallab88d972009-08-31 22:39:49 +00004488 // Also update the scope-based lookup if the target context's
4489 // lookup context is in lexical scope.
4490 if (!CurContext->isDependentContext()) {
4491 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004492 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004493 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004494 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004495 }
John McCall02cace72009-08-28 07:59:38 +00004496
4497 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004498 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004499 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004500 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004501 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004502
Douglas Gregor182ddf02009-09-28 00:08:27 +00004503 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004504}
4505
Chris Lattnerb28317a2009-03-28 19:18:32 +00004506void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004507 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Chris Lattnerb28317a2009-03-28 19:18:32 +00004509 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004510 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4511 if (!Fn) {
4512 Diag(DelLoc, diag::err_deleted_non_function);
4513 return;
4514 }
4515 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4516 Diag(DelLoc, diag::err_deleted_decl_not_first);
4517 Diag(Prev->getLocation(), diag::note_previous_declaration);
4518 // If the declaration wasn't the first, we delete the function anyway for
4519 // recovery.
4520 }
4521 Fn->setDeleted();
4522}
Sebastian Redl13e88542009-04-27 21:33:24 +00004523
4524static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4525 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4526 ++CI) {
4527 Stmt *SubStmt = *CI;
4528 if (!SubStmt)
4529 continue;
4530 if (isa<ReturnStmt>(SubStmt))
4531 Self.Diag(SubStmt->getSourceRange().getBegin(),
4532 diag::err_return_in_constructor_handler);
4533 if (!isa<Expr>(SubStmt))
4534 SearchForReturnInStmt(Self, SubStmt);
4535 }
4536}
4537
4538void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4539 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4540 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4541 SearchForReturnInStmt(*this, Handler);
4542 }
4543}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004544
Mike Stump1eb44332009-09-09 15:08:12 +00004545bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004546 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004547 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4548 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004549
4550 QualType CNewTy = Context.getCanonicalType(NewTy);
4551 QualType COldTy = Context.getCanonicalType(OldTy);
4552
Mike Stump1eb44332009-09-09 15:08:12 +00004553 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004554 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4555 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004556
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004557 // Check if the return types are covariant
4558 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004560 /// Both types must be pointers or references to classes.
4561 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4562 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4563 NewClassTy = NewPT->getPointeeType();
4564 OldClassTy = OldPT->getPointeeType();
4565 }
4566 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4567 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4568 NewClassTy = NewRT->getPointeeType();
4569 OldClassTy = OldRT->getPointeeType();
4570 }
4571 }
Mike Stump1eb44332009-09-09 15:08:12 +00004572
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004573 // The return types aren't either both pointers or references to a class type.
4574 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004575 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004576 diag::err_different_return_type_for_overriding_virtual_function)
4577 << New->getDeclName() << NewTy << OldTy;
4578 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004580 return true;
4581 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004582
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004583 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4584 // Check if the new class derives from the old class.
4585 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4586 Diag(New->getLocation(),
4587 diag::err_covariant_return_not_derived)
4588 << New->getDeclName() << NewTy << OldTy;
4589 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4590 return true;
4591 }
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004593 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004594 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004595 diag::err_covariant_return_inaccessible_base,
4596 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4597 // FIXME: Should this point to the return type?
4598 New->getLocation(), SourceRange(), New->getDeclName())) {
4599 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4600 return true;
4601 }
4602 }
Mike Stump1eb44332009-09-09 15:08:12 +00004603
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004604 // The qualifiers of the return types must be the same.
4605 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4606 Diag(New->getLocation(),
4607 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004608 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004609 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4610 return true;
4611 };
Mike Stump1eb44332009-09-09 15:08:12 +00004612
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004613
4614 // The new class type must have the same or less qualifiers as the old type.
4615 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4616 Diag(New->getLocation(),
4617 diag::err_covariant_return_type_class_type_more_qualified)
4618 << New->getDeclName() << NewTy << OldTy;
4619 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4620 return true;
4621 };
Mike Stump1eb44332009-09-09 15:08:12 +00004622
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004623 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004624}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004625
Sebastian Redl23c7d062009-07-07 20:29:57 +00004626bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump1eb44332009-09-09 15:08:12 +00004627 const CXXMethodDecl *Old) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00004628 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4629 diag::note_overridden_virtual_function,
John McCall183700f2009-09-21 23:43:11 +00004630 Old->getType()->getAs<FunctionProtoType>(),
Sebastian Redl23c7d062009-07-07 20:29:57 +00004631 Old->getLocation(),
John McCall183700f2009-09-21 23:43:11 +00004632 New->getType()->getAs<FunctionProtoType>(),
Sebastian Redl23c7d062009-07-07 20:29:57 +00004633 New->getLocation());
4634}
4635
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004636/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4637/// initializer for the declaration 'Dcl'.
4638/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4639/// static data member of class X, names should be looked up in the scope of
4640/// class X.
4641void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004642 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004643
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004644 Decl *D = Dcl.getAs<Decl>();
4645 // If there is no declaration, there was an error parsing it.
4646 if (D == 0)
4647 return;
4648
4649 // Check whether it is a declaration with a nested name specifier like
4650 // int foo::bar;
4651 if (!D->isOutOfLine())
4652 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004653
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004654 // C++ [basic.lookup.unqual]p13
4655 //
4656 // A name used in the definition of a static data member of class X
4657 // (after the qualified-id of the static member) is looked up as if the name
4658 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004659
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004660 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004661 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004662}
4663
4664/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4665/// initializer for the declaration 'Dcl'.
4666void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004667 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004669 Decl *D = Dcl.getAs<Decl>();
4670 // If there is no declaration, there was an error parsing it.
4671 if (D == 0)
4672 return;
4673
4674 // Check whether it is a declaration with a nested name specifier like
4675 // int foo::bar;
4676 if (!D->isOutOfLine())
4677 return;
4678
4679 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004680 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004681}