blob: ab90a80cabb9a2d00c629f075bc0ae0853b740b1 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000273 // FIXME: If the parameter doesn't have an identifier then the location
274 // points to the '=' which means that the fixit hint won't remove any
275 // extra spaces between the type and the '='.
276 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000277 if (NewParam->getIdentifier())
278 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000279
Mike Stump1eb44332009-09-09 15:08:12 +0000280 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000282 << NewParam->getDefaultArgRange()
283 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
284 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000356 }
357 }
358
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000359 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000363
Douglas Gregorcda9c672009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 else
Mike Stump1eb44332009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
434 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000448 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000449 SourceLocation BaseLoc) {
450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460 Class->getTagKind() == RecordDecl::TK_class,
461 Access, BaseType);
462
463 // Base specifiers must be record types.
464 if (!BaseType->isRecordType()) {
465 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466 return 0;
467 }
468
469 // C++ [class.union]p1:
470 // A union shall not be used as a base class.
471 if (BaseType->isUnionType()) {
472 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473 return 0;
474 }
475
476 // C++ [class.derived]p2:
477 // The class-name in a base-specifier shall not be an incompletely
478 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000479 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000480 PDiag(diag::err_incomplete_base_class)
481 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 return 0;
483
Eli Friedman1d954f62009-08-15 21:55:26 +0000484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 assert(BaseDecl && "Record type has no declaration");
487 BaseDecl = BaseDecl->getDefinition(Context);
488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000489 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000491
Sean Huntbbd37c62009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000497 return 0;
498 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499
Eli Friedmand0137332009-12-05 23:03:49 +0000500 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000501
502 // Create the base specifier.
503 // FIXME: Allocate via ASTContext?
504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505 Class->getTagKind() == RecordDecl::TK_class,
506 Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510 const CXXRecordDecl *BaseClass,
511 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000512 // A class with a non-empty base class is not empty.
513 // FIXME: Standard ref?
514 if (!BaseClass->isEmpty())
515 Class->setEmpty(false);
516
517 // C++ [class.virtual]p1:
518 // A class that [...] inherits a virtual function is called a polymorphic
519 // class.
520 if (BaseClass->isPolymorphic())
521 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000522
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is [...] a class with [...] no base classes [...].
525 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000526
527 // C++ [class]p4:
528 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 Class->setPOD(false);
530
Anders Carlsson51f94042009-12-03 17:49:57 +0000531 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000532 // C++ [class.ctor]p5:
533 // A constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000535
536 // C++ [class.copy]p6:
537 // A copy constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialCopyConstructor(false);
539
540 // C++ [class.copy]p11:
541 // A copy assignment operator is trivial if its class has no virtual
542 // base classes.
543 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000544
545 // C++0x [meta.unary.prop] is_empty:
546 // T is a class type, but not a union type, with ... no virtual base
547 // classes
548 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000549 } else {
550 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000551 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000553 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000554 Class->setHasTrivialConstructor(false);
555
556 // C++ [class.copy]p6:
557 // A copy constructor is trivial if all the direct base classes of its
558 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialCopyConstructor(false);
561
562 // C++ [class.copy]p11:
563 // A copy assignment operator is trivial if all the direct base classes
564 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000567 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000568
569 // C++ [class.ctor]p3:
570 // A destructor is trivial if all the direct base classes of its class
571 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000572 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000573 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574}
575
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000578/// example:
579/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000580/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000581Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 bool Virtual, AccessSpecifier Access,
584 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000585 if (!classdecl)
586 return true;
587
Douglas Gregor40808ce2009-03-09 23:48:35 +0000588 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000590 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
592 Virtual, Access,
593 BaseType, BaseLoc))
594 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000597}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599/// \brief Performs the actual work of attaching the given base class
600/// specifiers to a C++ class.
601bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
602 unsigned NumBases) {
603 if (NumBases == 0)
604 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605
606 // Used to keep track of which base types we have already seen, so
607 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608 // that the key is always the unqualified canonical type of the base
609 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
611
612 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000616 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000618 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 if (KnownBaseTypes[NewBaseType]) {
621 // C++ [class.mi]p3:
622 // A class shall not be specified as a direct base class of a
623 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000625 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000626 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the duplicate base class specifier; we're going to
630 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000631 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632
633 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000634 } else {
635 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 KnownBaseTypes[NewBaseType] = Bases[idx];
637 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 }
639 }
640
641 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000642 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the remaining (good) base class specifiers, since their
645 // data has been copied into the CXXRecordDecl.
646 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000647 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648
649 return Invalid;
650}
651
652/// ActOnBaseSpecifiers - Attach the given base specifiers to the
653/// class, after checking whether there are any duplicate base
654/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000655void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000656 unsigned NumBases) {
657 if (!ClassDecl || !Bases || !NumBases)
658 return;
659
660 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000661 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000664
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665/// \brief Determine whether the type \p Derived is a C++ class that is
666/// derived from the type \p Base.
667bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
668 if (!getLangOptions().CPlusPlus)
669 return false;
670
671 const RecordType *DerivedRT = Derived->getAs<RecordType>();
672 if (!DerivedRT)
673 return false;
674
675 const RecordType *BaseRT = Base->getAs<RecordType>();
676 if (!BaseRT)
677 return false;
678
679 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
680 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
681 return DerivedRD->isDerivedFrom(BaseRD);
682}
683
684/// \brief Determine whether the type \p Derived is a C++ class that is
685/// derived from the type \p Base.
686bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
687 if (!getLangOptions().CPlusPlus)
688 return false;
689
690 const RecordType *DerivedRT = Derived->getAs<RecordType>();
691 if (!DerivedRT)
692 return false;
693
694 const RecordType *BaseRT = Base->getAs<RecordType>();
695 if (!BaseRT)
696 return false;
697
698 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
699 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
700 return DerivedRD->isDerivedFrom(BaseRD, Paths);
701}
702
703/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
704/// conversion (where Derived and Base are class types) is
705/// well-formed, meaning that the conversion is unambiguous (and
706/// that all of the base classes are accessible). Returns true
707/// and emits a diagnostic if the code is ill-formed, returns false
708/// otherwise. Loc is the location where this routine should point to
709/// if there is an error, and Range is the source range to highlight
710/// if there is an error.
711bool
712Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
713 unsigned InaccessibleBaseID,
714 unsigned AmbigiousBaseConvID,
715 SourceLocation Loc, SourceRange Range,
716 DeclarationName Name) {
717 // First, determine whether the path from Derived to Base is
718 // ambiguous. This is slightly more expensive than checking whether
719 // the Derived to Base conversion exists, because here we need to
720 // explore multiple paths to determine if there is an ambiguity.
721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
722 /*DetectVirtual=*/false);
723 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
724 assert(DerivationOkay &&
725 "Can only be used with a derived-to-base conversion");
726 (void)DerivationOkay;
727
728 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000729 if (InaccessibleBaseID == 0)
730 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000731 // Check that the base class can be accessed.
732 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
733 Name);
734 }
735
736 // We know that the derived-to-base conversion is ambiguous, and
737 // we're going to produce a diagnostic. Perform the derived-to-base
738 // search just one more time to compute all of the possible paths so
739 // that we can print them out. This is more expensive than any of
740 // the previous derived-to-base checks we've done, but at this point
741 // performance isn't as much of an issue.
742 Paths.clear();
743 Paths.setRecordingPaths(true);
744 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
745 assert(StillOkay && "Can only be used with a derived-to-base conversion");
746 (void)StillOkay;
747
748 // Build up a textual representation of the ambiguous paths, e.g.,
749 // D -> B -> A, that will be used to illustrate the ambiguous
750 // conversions in the diagnostic. We only print one of the paths
751 // to each base class subobject.
752 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
753
754 Diag(Loc, AmbigiousBaseConvID)
755 << Derived << Base << PathDisplayStr << Range << Name;
756 return true;
757}
758
759bool
760Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000761 SourceLocation Loc, SourceRange Range,
762 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000763 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000764 IgnoreAccess ? 0 :
765 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000766 diag::err_ambiguous_derived_to_base_conv,
767 Loc, Range, DeclarationName());
768}
769
770
771/// @brief Builds a string representing ambiguous paths from a
772/// specific derived class to different subobjects of the same base
773/// class.
774///
775/// This function builds a string that can be used in error messages
776/// to show the different paths that one can take through the
777/// inheritance hierarchy to go from the derived class to different
778/// subobjects of a base class. The result looks something like this:
779/// @code
780/// struct D -> struct B -> struct A
781/// struct D -> struct C -> struct A
782/// @endcode
783std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
784 std::string PathDisplayStr;
785 std::set<unsigned> DisplayedPaths;
786 for (CXXBasePaths::paths_iterator Path = Paths.begin();
787 Path != Paths.end(); ++Path) {
788 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
789 // We haven't displayed a path to this particular base
790 // class subobject yet.
791 PathDisplayStr += "\n ";
792 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
793 for (CXXBasePath::const_iterator Element = Path->begin();
794 Element != Path->end(); ++Element)
795 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
796 }
797 }
798
799 return PathDisplayStr;
800}
801
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000802//===----------------------------------------------------------------------===//
803// C++ class member Handling
804//===----------------------------------------------------------------------===//
805
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000806/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
807/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
808/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000809/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000810Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000812 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000813 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
814 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000815 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000816 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000817 Expr *BitWidth = static_cast<Expr*>(BW);
818 Expr *Init = static_cast<Expr*>(InitExpr);
819 SourceLocation Loc = D.getIdentifierLoc();
820
Sebastian Redl669d5d72008-11-14 23:42:31 +0000821 bool isFunc = D.isFunctionDeclarator();
822
John McCall67d1a672009-08-06 02:15:43 +0000823 assert(!DS.isFriendSpecified());
824
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000825 // C++ 9.2p6: A member shall not be declared to have automatic storage
826 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000827 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
828 // data members and cannot be applied to names declared const or static,
829 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000830 switch (DS.getStorageClassSpec()) {
831 case DeclSpec::SCS_unspecified:
832 case DeclSpec::SCS_typedef:
833 case DeclSpec::SCS_static:
834 // FALL THROUGH.
835 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000836 case DeclSpec::SCS_mutable:
837 if (isFunc) {
838 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000839 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000840 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000841 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Sebastian Redla11f42f2008-11-17 23:24:37 +0000843 // FIXME: It would be nicer if the keyword was ignored only for this
844 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000845 D.getMutableDeclSpec().ClearStorageClassSpecs();
846 } else {
847 QualType T = GetTypeForDeclarator(D, S);
848 diag::kind err = static_cast<diag::kind>(0);
849 if (T->isReferenceType())
850 err = diag::err_mutable_reference;
851 else if (T.isConstQualified())
852 err = diag::err_mutable_const;
853 if (err != 0) {
854 if (DS.getStorageClassSpecLoc().isValid())
855 Diag(DS.getStorageClassSpecLoc(), err);
856 else
857 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000858 // FIXME: It would be nicer if the keyword was ignored only for this
859 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000860 D.getMutableDeclSpec().ClearStorageClassSpecs();
861 }
862 }
863 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864 default:
865 if (DS.getStorageClassSpecLoc().isValid())
866 Diag(DS.getStorageClassSpecLoc(),
867 diag::err_storageclass_invalid_for_member);
868 else
869 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
870 D.getMutableDeclSpec().ClearStorageClassSpecs();
871 }
872
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000873 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000874 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000875 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000876 // Check also for this case:
877 //
878 // typedef int f();
879 // f a;
880 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000881 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000882 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000883 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884
Sebastian Redl669d5d72008-11-14 23:42:31 +0000885 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
886 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000887 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888
889 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000890 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000891 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000892 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
893 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000894 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000895 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000896 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000897 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000898 if (!Member) {
899 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000900 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000901 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000902
903 // Non-instance-fields can't have a bitfield.
904 if (BitWidth) {
905 if (Member->isInvalidDecl()) {
906 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000907 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000908 // C++ 9.6p3: A bit-field shall not be a static member.
909 // "static member 'A' cannot be a bit-field"
910 Diag(Loc, diag::err_static_not_bitfield)
911 << Name << BitWidth->getSourceRange();
912 } else if (isa<TypedefDecl>(Member)) {
913 // "typedef member 'x' cannot be a bit-field"
914 Diag(Loc, diag::err_typedef_not_bitfield)
915 << Name << BitWidth->getSourceRange();
916 } else {
917 // A function typedef ("typedef int f(); f a;").
918 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
919 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000920 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000921 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner8b963ef2009-03-05 23:01:03 +0000924 DeleteExpr(BitWidth);
925 BitWidth = 0;
926 Member->setInvalidDecl();
927 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000928
929 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregor37b372b2009-08-20 22:52:58 +0000931 // If we have declared a member function template, set the access of the
932 // templated declaration as well.
933 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
934 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000935 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000936
Douglas Gregor10bd3682008-11-17 22:58:34 +0000937 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000938
Douglas Gregor021c3b32009-03-11 23:00:04 +0000939 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000940 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000941 if (Deleted) // FIXME: Source location is not very good.
942 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000943
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000944 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000945 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000946 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000948 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949}
950
Douglas Gregor7ad83902008-11-05 04:29:56 +0000951/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000952Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000953Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000954 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000955 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000956 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000957 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000958 SourceLocation IdLoc,
959 SourceLocation LParenLoc,
960 ExprTy **Args, unsigned NumArgs,
961 SourceLocation *CommaLocs,
962 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000963 if (!ConstructorD)
964 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000966 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
968 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000969 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000970 if (!Constructor) {
971 // The user wrote a constructor initializer on a function that is
972 // not a C++ constructor. Ignore the error for now, because we may
973 // have more member initializers coming; we'll diagnose it just
974 // once in ActOnMemInitializers.
975 return true;
976 }
977
978 CXXRecordDecl *ClassDecl = Constructor->getParent();
979
980 // C++ [class.base.init]p2:
981 // Names in a mem-initializer-id are looked up in the scope of the
982 // constructor’s class and, if not found in that scope, are looked
983 // up in the scope containing the constructor’s
984 // definition. [Note: if the constructor’s class contains a member
985 // with the same name as a direct or virtual base class of the
986 // class, a mem-initializer-id naming the member or base class and
987 // composed of a single identifier refers to the class member. A
988 // mem-initializer-id for the hidden base class may be specified
989 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000990 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000991 // Look for a member, first.
992 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000993 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000994 = ClassDecl->lookup(MemberOrBase);
995 if (Result.first != Result.second)
996 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000997
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000998 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000999
Eli Friedman59c04372009-07-29 19:44:27 +00001000 if (Member)
1001 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001002 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001003 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001004 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001005 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001006 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001007
1008 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001009 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001010 } else {
1011 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1012 LookupParsedName(R, S, &SS);
1013
1014 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1015 if (!TyD) {
1016 if (R.isAmbiguous()) return true;
1017
1018 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1019 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1020 return true;
1021 }
1022
1023 BaseType = Context.getTypeDeclType(TyD);
1024 if (SS.isSet()) {
1025 NestedNameSpecifier *Qualifier =
1026 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1027
1028 // FIXME: preserve source range information
1029 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1030 }
1031 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
John McCalla93c9342009-12-07 02:54:59 +00001033 if (!TInfo)
1034 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001035
John McCalla93c9342009-12-07 02:54:59 +00001036 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001037 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001038}
1039
John McCallb4190042009-11-04 23:02:40 +00001040/// Checks an initializer expression for use of uninitialized fields, such as
1041/// containing the field that is being initialized. Returns true if there is an
1042/// uninitialized field was used an updates the SourceLocation parameter; false
1043/// otherwise.
1044static bool InitExprContainsUninitializedFields(const Stmt* S,
1045 const FieldDecl* LhsField,
1046 SourceLocation* L) {
1047 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1048 if (ME) {
1049 const NamedDecl* RhsField = ME->getMemberDecl();
1050 if (RhsField == LhsField) {
1051 // Initializing a field with itself. Throw a warning.
1052 // But wait; there are exceptions!
1053 // Exception #1: The field may not belong to this record.
1054 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1055 const Expr* base = ME->getBase();
1056 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1057 // Even though the field matches, it does not belong to this record.
1058 return false;
1059 }
1060 // None of the exceptions triggered; return true to indicate an
1061 // uninitialized field was used.
1062 *L = ME->getMemberLoc();
1063 return true;
1064 }
1065 }
1066 bool found = false;
1067 for (Stmt::const_child_iterator it = S->child_begin();
1068 it != S->child_end() && found == false;
1069 ++it) {
1070 if (isa<CallExpr>(S)) {
1071 // Do not descend into function calls or constructors, as the use
1072 // of an uninitialized field may be valid. One would have to inspect
1073 // the contents of the function/ctor to determine if it is safe or not.
1074 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1075 // may be safe, depending on what the function/ctor does.
1076 continue;
1077 }
1078 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1079 }
1080 return found;
1081}
1082
Eli Friedman59c04372009-07-29 19:44:27 +00001083Sema::MemInitResult
1084Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1085 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001086 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001087 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001088 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1089 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1090 ExprTemporaries.clear();
1091
John McCallb4190042009-11-04 23:02:40 +00001092 // Diagnose value-uses of fields to initialize themselves, e.g.
1093 // foo(foo)
1094 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001095 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001096 for (unsigned i = 0; i < NumArgs; ++i) {
1097 SourceLocation L;
1098 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1099 // FIXME: Return true in the case when other fields are used before being
1100 // uninitialized. For example, let this field be the i'th field. When
1101 // initializing the i'th field, throw a warning if any of the >= i'th
1102 // fields are used, as they are not yet initialized.
1103 // Right now we are only handling the case where the i'th field uses
1104 // itself in its initializer.
1105 Diag(L, diag::warn_field_is_uninit);
1106 }
1107 }
1108
Eli Friedman59c04372009-07-29 19:44:27 +00001109 bool HasDependentArg = false;
1110 for (unsigned i = 0; i < NumArgs; i++)
1111 HasDependentArg |= Args[i]->isTypeDependent();
1112
1113 CXXConstructorDecl *C = 0;
1114 QualType FieldType = Member->getType();
1115 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1116 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001117 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Eli Friedman59c04372009-07-29 19:44:27 +00001118 if (FieldType->isDependentType()) {
1119 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001120 } else if (FieldType->isRecordType()) {
1121 // Member is a record (struct/union/class), so pass the initializer
1122 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001123 if (!HasDependentArg) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00001124 C = PerformInitializationByConstructor(FieldType,
1125 MultiExprArg(*this,
1126 (void**)Args,
1127 NumArgs),
1128 IdLoc,
1129 SourceRange(IdLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001130 Member->getDeclName(),
1131 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001132 ConstructorArgs);
1133
1134 if (C) {
1135 // Take over the constructor arguments as our own.
1136 NumArgs = ConstructorArgs.size();
1137 Args = (Expr **)ConstructorArgs.take();
1138 }
1139 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001140 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001141 // The member type is not a record type (or an array of record
1142 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001143 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001144 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1145 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001146 Expr *NewExp;
1147 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001148 if (FieldType->isReferenceType()) {
1149 Diag(IdLoc, diag::err_null_intialized_reference_member)
1150 << Member->getDeclName();
1151 return Diag(Member->getLocation(), diag::note_declared_at);
1152 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001153 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1154 NumArgs = 1;
1155 }
1156 else
1157 NewExp = (Expr*)Args[0];
Douglas Gregor68647482009-12-16 03:45:30 +00001158 if (PerformCopyInitialization(NewExp, FieldType, AA_Passing))
Eli Friedman59c04372009-07-29 19:44:27 +00001159 return true;
1160 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001161 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001162
1163 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1164 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1165 ExprTemporaries.clear();
1166
Eli Friedman59c04372009-07-29 19:44:27 +00001167 // FIXME: Perform direct initialization of the member.
Douglas Gregor802ab452009-12-02 22:36:29 +00001168 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1169 C, LParenLoc, (Expr **)Args,
1170 NumArgs, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001171}
1172
1173Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001174Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001175 Expr **Args, unsigned NumArgs,
1176 SourceLocation LParenLoc, SourceLocation RParenLoc,
1177 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001178 bool HasDependentArg = false;
1179 for (unsigned i = 0; i < NumArgs; i++)
1180 HasDependentArg |= Args[i]->isTypeDependent();
1181
John McCalla93c9342009-12-07 02:54:59 +00001182 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman59c04372009-07-29 19:44:27 +00001183 if (!BaseType->isDependentType()) {
1184 if (!BaseType->isRecordType())
Douglas Gregor802ab452009-12-02 22:36:29 +00001185 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCalla93c9342009-12-07 02:54:59 +00001186 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001187
1188 // C++ [class.base.init]p2:
1189 // [...] Unless the mem-initializer-id names a nonstatic data
1190 // member of the constructor’s class or a direct or virtual base
1191 // of that class, the mem-initializer is ill-formed. A
1192 // mem-initializer-list can initialize a base class using any
1193 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Eli Friedman59c04372009-07-29 19:44:27 +00001195 // First, check for a direct base class.
1196 const CXXBaseSpecifier *DirectBaseSpec = 0;
1197 for (CXXRecordDecl::base_class_const_iterator Base =
1198 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001199 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001200 // We found a direct base of this type. That's what we're
1201 // initializing.
1202 DirectBaseSpec = &*Base;
1203 break;
1204 }
1205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Eli Friedman59c04372009-07-29 19:44:27 +00001207 // Check for a virtual base class.
1208 // FIXME: We might be able to short-circuit this if we know in advance that
1209 // there are no virtual bases.
1210 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1212 // We haven't found a base yet; search the class hierarchy for a
1213 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1215 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001216 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001218 Path != Paths.end(); ++Path) {
1219 if (Path->back().Base->isVirtual()) {
1220 VirtualBaseSpec = Path->back().Base;
1221 break;
1222 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001223 }
1224 }
1225 }
Eli Friedman59c04372009-07-29 19:44:27 +00001226
1227 // C++ [base.class.init]p2:
1228 // If a mem-initializer-id is ambiguous because it designates both
1229 // a direct non-virtual base class and an inherited virtual base
1230 // class, the mem-initializer is ill-formed.
1231 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001232 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCalla93c9342009-12-07 02:54:59 +00001233 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001234 // C++ [base.class.init]p2:
1235 // Unless the mem-initializer-id names a nonstatic data membeer of the
1236 // constructor's class ot a direst or virtual base of that class, the
1237 // mem-initializer is ill-formed.
1238 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001239 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1240 << BaseType << ClassDecl->getNameAsCString()
John McCalla93c9342009-12-07 02:54:59 +00001241 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregor7ad83902008-11-05 04:29:56 +00001242 }
1243
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001244 CXXConstructorDecl *C = 0;
Eli Friedmane6d11b72009-12-25 23:59:21 +00001245 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Eli Friedman59c04372009-07-29 19:44:27 +00001246 if (!BaseType->isDependentType() && !HasDependentArg) {
1247 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001248 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001249
1250 C = PerformInitializationByConstructor(BaseType,
1251 MultiExprArg(*this,
1252 (void**)Args, NumArgs),
Douglas Gregor802ab452009-12-02 22:36:29 +00001253 BaseLoc,
1254 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001255 Name,
1256 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001257 ConstructorArgs);
1258 if (C) {
1259 // Take over the constructor arguments as our own.
1260 NumArgs = ConstructorArgs.size();
1261 Args = (Expr **)ConstructorArgs.take();
1262 }
Eli Friedman59c04372009-07-29 19:44:27 +00001263 }
1264
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001265 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1266 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1267 ExprTemporaries.clear();
1268
John McCalla93c9342009-12-07 02:54:59 +00001269 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregor802ab452009-12-02 22:36:29 +00001270 LParenLoc, (Expr **)Args,
1271 NumArgs, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001272}
1273
Eli Friedman80c30da2009-11-09 19:20:36 +00001274bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001275Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001276 CXXBaseOrMemberInitializer **Initializers,
1277 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001278 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001279 // We need to build the initializer AST according to order of construction
1280 // and not what user specified in the Initializers list.
1281 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1282 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1283 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1284 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001285 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001287 for (unsigned i = 0; i < NumInitializers; i++) {
1288 CXXBaseOrMemberInitializer *Member = Initializers[i];
1289 if (Member->isBaseInitializer()) {
1290 if (Member->getBaseClass()->isDependentType())
1291 HasDependentBaseInit = true;
1292 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1293 } else {
1294 AllBaseFields[Member->getMember()] = Member;
1295 }
1296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001298 if (HasDependentBaseInit) {
1299 // FIXME. This does not preserve the ordering of the initializers.
1300 // Try (with -Wreorder)
1301 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001302 // template<class X> struct B : A<X> {
1303 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001304 // int x1;
1305 // };
1306 // B<int> x;
1307 // On seeing one dependent type, we should essentially exit this routine
1308 // while preserving user-declared initializer list. When this routine is
1309 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001310 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001312 // If we have a dependent base initialization, we can't determine the
1313 // association between initializers and bases; just dump the known
1314 // initializers into the list, and don't try to deal with other bases.
1315 for (unsigned i = 0; i < NumInitializers; i++) {
1316 CXXBaseOrMemberInitializer *Member = Initializers[i];
1317 if (Member->isBaseInitializer())
1318 AllToInit.push_back(Member);
1319 }
1320 } else {
1321 // Push virtual bases before others.
1322 for (CXXRecordDecl::base_class_iterator VBase =
1323 ClassDecl->vbases_begin(),
1324 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1325 if (VBase->getType()->isDependentType())
1326 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001327 if (CXXBaseOrMemberInitializer *Value
1328 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001329 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001330 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001331 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001332 CXXRecordDecl *VBaseDecl =
Douglas Gregor802ab452009-12-02 22:36:29 +00001333 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001334 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001335 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001336 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001337 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1338 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1339 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001340 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001341 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001342 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001343 continue;
1344 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001345
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001346 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1347 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1348 Constructor->getLocation(), CtorArgs))
1349 continue;
1350
1351 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1352
Anders Carlsson8db68da2009-11-13 20:11:49 +00001353 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001354 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1355 // necessary.
1356 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001357 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001358 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001359 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001360 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001361 SourceLocation()),
1362 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001363 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001364 CtorArgs.takeAs<Expr>(),
1365 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001366 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001367 AllToInit.push_back(Member);
1368 }
1369 }
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001371 for (CXXRecordDecl::base_class_iterator Base =
1372 ClassDecl->bases_begin(),
1373 E = ClassDecl->bases_end(); Base != E; ++Base) {
1374 // Virtuals are in the virtual base list and already constructed.
1375 if (Base->isVirtual())
1376 continue;
1377 // Skip dependent types.
1378 if (Base->getType()->isDependentType())
1379 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001380 if (CXXBaseOrMemberInitializer *Value
1381 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001382 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001383 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001384 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001385 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001386 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001387 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001388 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001389 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001390 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1391 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1392 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001393 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001394 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001395 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001396 continue;
1397 }
1398
1399 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1400 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1401 Constructor->getLocation(), CtorArgs))
1402 continue;
1403
1404 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001405
Anders Carlsson8db68da2009-11-13 20:11:49 +00001406 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001407 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1408 // necessary.
1409 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001410 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001411 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001412 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001413 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001414 SourceLocation()),
1415 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001416 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001417 CtorArgs.takeAs<Expr>(),
1418 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001419 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001420 AllToInit.push_back(Member);
1421 }
1422 }
1423 }
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001425 // non-static data members.
1426 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1427 E = ClassDecl->field_end(); Field != E; ++Field) {
1428 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001429 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001430 Field->getType()->getAs<RecordType>()) {
1431 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001432 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001433 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001434 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1435 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1436 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1437 // set to the anonymous union data member used in the initializer
1438 // list.
1439 Value->setMember(*Field);
1440 Value->setAnonUnionMember(*FA);
1441 AllToInit.push_back(Value);
1442 break;
1443 }
1444 }
1445 }
1446 continue;
1447 }
1448 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1449 AllToInit.push_back(Value);
1450 continue;
1451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Eli Friedman49c16da2009-11-09 01:05:47 +00001453 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001454 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001455
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001456 QualType FT = Context.getBaseElementType((*Field)->getType());
1457 if (const RecordType* RT = FT->getAs<RecordType>()) {
1458 CXXConstructorDecl *Ctor =
1459 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001460 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001461 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1462 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1463 << 1 << (*Field)->getDeclName();
1464 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001465 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001466 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001467 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001468 continue;
1469 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001470
1471 if (FT.isConstQualified() && Ctor->isTrivial()) {
1472 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1473 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1474 << 1 << (*Field)->getDeclName();
1475 Diag((*Field)->getLocation(), diag::note_declared_at);
1476 HadError = true;
1477 }
1478
1479 // Don't create initializers for trivial constructors, since they don't
1480 // actually need to be run.
1481 if (Ctor->isTrivial())
1482 continue;
1483
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001484 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1485 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1486 Constructor->getLocation(), CtorArgs))
1487 continue;
1488
Anders Carlsson8db68da2009-11-13 20:11:49 +00001489 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1490 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1491 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001492 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001493 new (Context) CXXBaseOrMemberInitializer(Context,
1494 *Field, SourceLocation(),
1495 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001496 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001497 CtorArgs.takeAs<Expr>(),
1498 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001499 SourceLocation());
1500
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001501 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001502 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001503 }
1504 else if (FT->isReferenceType()) {
1505 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001506 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1507 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001508 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001509 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001510 }
1511 else if (FT.isConstQualified()) {
1512 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001513 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1514 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001515 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001516 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001517 }
1518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001520 NumInitializers = AllToInit.size();
1521 if (NumInitializers > 0) {
1522 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1523 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1524 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001526 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1527 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1528 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1529 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001530
1531 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001532}
1533
Eli Friedman6347f422009-07-21 19:28:10 +00001534static void *GetKeyForTopLevelField(FieldDecl *Field) {
1535 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001536 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001537 if (RT->getDecl()->isAnonymousStructOrUnion())
1538 return static_cast<void *>(RT->getDecl());
1539 }
1540 return static_cast<void *>(Field);
1541}
1542
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001543static void *GetKeyForBase(QualType BaseType) {
1544 if (const RecordType *RT = BaseType->getAs<RecordType>())
1545 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001547 assert(0 && "Unexpected base type!");
1548 return 0;
1549}
1550
Mike Stump1eb44332009-09-09 15:08:12 +00001551static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001552 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001553 // For fields injected into the class via declaration of an anonymous union,
1554 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001555 if (Member->isMemberInitializer()) {
1556 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Eli Friedman49c16da2009-11-09 01:05:47 +00001558 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001559 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001560 // in AnonUnionMember field.
1561 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1562 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001563 if (Field->getDeclContext()->isRecord()) {
1564 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1565 if (RD->isAnonymousStructOrUnion())
1566 return static_cast<void *>(RD);
1567 }
1568 return static_cast<void *>(Field);
1569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001571 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001572}
1573
John McCall6aee6212009-11-04 23:13:52 +00001574/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001575void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001576 SourceLocation ColonLoc,
1577 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001578 if (!ConstructorDecl)
1579 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001580
1581 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
1583 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001584 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Anders Carlssona7b35212009-03-25 02:58:17 +00001586 if (!Constructor) {
1587 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1588 return;
1589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001591 if (!Constructor->isDependentContext()) {
1592 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1593 bool err = false;
1594 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001595 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001596 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1597 void *KeyToMember = GetKeyForMember(Member);
1598 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1599 if (!PrevMember) {
1600 PrevMember = Member;
1601 continue;
1602 }
1603 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001604 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001605 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001606 << Field->getNameAsString()
1607 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001608 else {
1609 Type *BaseClass = Member->getBaseClass();
1610 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001611 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001612 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001613 << QualType(BaseClass, 0)
1614 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001615 }
1616 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1617 << 0;
1618 err = true;
1619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001621 if (err)
1622 return;
1623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Eli Friedman49c16da2009-11-09 01:05:47 +00001625 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001626 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001627 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001629 if (Constructor->isDependentContext())
1630 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001631
1632 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001633 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001634 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001635 Diagnostic::Ignored)
1636 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001638 // Also issue warning if order of ctor-initializer list does not match order
1639 // of 1) base class declarations and 2) order of non-static data members.
1640 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001642 CXXRecordDecl *ClassDecl
1643 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1644 // Push virtual bases before others.
1645 for (CXXRecordDecl::base_class_iterator VBase =
1646 ClassDecl->vbases_begin(),
1647 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001648 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001650 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1651 E = ClassDecl->bases_end(); Base != E; ++Base) {
1652 // Virtuals are alread in the virtual base list and are constructed
1653 // first.
1654 if (Base->isVirtual())
1655 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001656 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001659 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1660 E = ClassDecl->field_end(); Field != E; ++Field)
1661 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001663 int Last = AllBaseOrMembers.size();
1664 int curIndex = 0;
1665 CXXBaseOrMemberInitializer *PrevMember = 0;
1666 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001667 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001668 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1669 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001670
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001671 for (; curIndex < Last; curIndex++)
1672 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1673 break;
1674 if (curIndex == Last) {
1675 assert(PrevMember && "Member not in member list?!");
1676 // Initializer as specified in ctor-initializer list is out of order.
1677 // Issue a warning diagnostic.
1678 if (PrevMember->isBaseInitializer()) {
1679 // Diagnostics is for an initialized base class.
1680 Type *BaseClass = PrevMember->getBaseClass();
1681 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001682 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001683 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001684 } else {
1685 FieldDecl *Field = PrevMember->getMember();
1686 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001687 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001688 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001689 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001690 // Also the note!
1691 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001692 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001693 diag::note_fieldorbase_initialized_here) << 0
1694 << Field->getNameAsString();
1695 else {
1696 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001697 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001698 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001699 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001700 }
1701 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001702 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001703 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001704 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001705 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001706 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001707}
1708
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001709void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001710Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1711 // Ignore dependent destructors.
1712 if (Destructor->isDependentContext())
1713 return;
1714
1715 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Anders Carlsson9f853df2009-11-17 04:44:12 +00001717 // Non-static data members.
1718 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1719 E = ClassDecl->field_end(); I != E; ++I) {
1720 FieldDecl *Field = *I;
1721
1722 QualType FieldType = Context.getBaseElementType(Field->getType());
1723
1724 const RecordType* RT = FieldType->getAs<RecordType>();
1725 if (!RT)
1726 continue;
1727
1728 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1729 if (FieldClassDecl->hasTrivialDestructor())
1730 continue;
1731
1732 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1733 MarkDeclarationReferenced(Destructor->getLocation(),
1734 const_cast<CXXDestructorDecl*>(Dtor));
1735 }
1736
1737 // Bases.
1738 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1739 E = ClassDecl->bases_end(); Base != E; ++Base) {
1740 // Ignore virtual bases.
1741 if (Base->isVirtual())
1742 continue;
1743
1744 // Ignore trivial destructors.
1745 CXXRecordDecl *BaseClassDecl
1746 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1747 if (BaseClassDecl->hasTrivialDestructor())
1748 continue;
1749
1750 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1751 MarkDeclarationReferenced(Destructor->getLocation(),
1752 const_cast<CXXDestructorDecl*>(Dtor));
1753 }
1754
1755 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001756 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1757 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001758 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001759 CXXRecordDecl *BaseClassDecl
1760 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1761 if (BaseClassDecl->hasTrivialDestructor())
1762 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001763
1764 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1765 MarkDeclarationReferenced(Destructor->getLocation(),
1766 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001767 }
1768}
1769
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001770void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001771 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001772 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001774 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
1776 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001777 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001778 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001779}
1780
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001781namespace {
1782 /// PureVirtualMethodCollector - traverses a class and its superclasses
1783 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001784 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001785 ASTContext &Context;
1786
Sebastian Redldfe292d2009-03-22 21:28:55 +00001787 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001788 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001789
1790 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001791 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001793 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001795 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001796 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001797 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001799 MethodList List;
1800 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001802 // Copy the temporary list to methods, and make sure to ignore any
1803 // null entries.
1804 for (size_t i = 0, e = List.size(); i != e; ++i) {
1805 if (List[i])
1806 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001807 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001810 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001812 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1813 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001814 };
Mike Stump1eb44332009-09-09 15:08:12 +00001815
1816 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001817 MethodList& Methods) {
1818 // First, collect the pure virtual methods for the base classes.
1819 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1820 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001821 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001822 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001823 if (BaseDecl && BaseDecl->isAbstract())
1824 Collect(BaseDecl, Methods);
1825 }
1826 }
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001828 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001829 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001831 MethodSetTy OverriddenMethods;
1832 size_t MethodsSize = Methods.size();
1833
Mike Stump1eb44332009-09-09 15:08:12 +00001834 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001835 i != e; ++i) {
1836 // Traverse the record, looking for methods.
1837 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001838 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001839 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001840 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Anders Carlsson27823022009-10-18 19:34:08 +00001842 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001843 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1844 E = MD->end_overridden_methods(); I != E; ++I) {
1845 // Keep track of the overridden methods.
1846 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001847 }
1848 }
1849 }
Mike Stump1eb44332009-09-09 15:08:12 +00001850
1851 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001852 // overridden.
1853 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1854 if (OverriddenMethods.count(Methods[i]))
1855 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001858 }
1859}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001860
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001861
Mike Stump1eb44332009-09-09 15:08:12 +00001862bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001863 unsigned DiagID, AbstractDiagSelID SelID,
1864 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001865 if (SelID == -1)
1866 return RequireNonAbstractType(Loc, T,
1867 PDiag(DiagID), CurrentRD);
1868 else
1869 return RequireNonAbstractType(Loc, T,
1870 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001871}
1872
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001873bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1874 const PartialDiagnostic &PD,
1875 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001876 if (!getLangOptions().CPlusPlus)
1877 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Anders Carlsson11f21a02009-03-23 19:10:31 +00001879 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001880 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001881 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Ted Kremenek6217b802009-07-29 21:53:49 +00001883 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001884 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001885 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001886 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001888 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001889 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001890 }
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Ted Kremenek6217b802009-07-29 21:53:49 +00001892 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001893 if (!RT)
1894 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001896 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1897 if (!RD)
1898 return false;
1899
Anders Carlssone65a3c82009-03-24 17:23:42 +00001900 if (CurrentRD && CurrentRD != RD)
1901 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001903 if (!RD->isAbstract())
1904 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001906 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001908 // Check if we've already emitted the list of pure virtual functions for this
1909 // class.
1910 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1911 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001913 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001914
1915 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001916 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1917 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001918
1919 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001920 MD->getDeclName();
1921 }
1922
1923 if (!PureVirtualClassDiagSet)
1924 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1925 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001927 return true;
1928}
1929
Anders Carlsson8211eff2009-03-24 01:19:16 +00001930namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001931 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001932 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1933 Sema &SemaRef;
1934 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Anders Carlssone65a3c82009-03-24 17:23:42 +00001936 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001937 bool Invalid = false;
1938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001939 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1940 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001941 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001942
Anders Carlsson8211eff2009-03-24 01:19:16 +00001943 return Invalid;
1944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Anders Carlssone65a3c82009-03-24 17:23:42 +00001946 public:
1947 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1948 : SemaRef(SemaRef), AbstractClass(ac) {
1949 Visit(SemaRef.Context.getTranslationUnitDecl());
1950 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001951
Anders Carlssone65a3c82009-03-24 17:23:42 +00001952 bool VisitFunctionDecl(const FunctionDecl *FD) {
1953 if (FD->isThisDeclarationADefinition()) {
1954 // No need to do the check if we're in a definition, because it requires
1955 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001956 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001957 return VisitDeclContext(FD);
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Anders Carlssone65a3c82009-03-24 17:23:42 +00001960 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001961 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001962 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001963 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1964 diag::err_abstract_type_in_decl,
1965 Sema::AbstractReturnType,
1966 AbstractClass);
1967
Mike Stump1eb44332009-09-09 15:08:12 +00001968 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001969 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001970 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001971 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001972 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001973 VD->getOriginalType(),
1974 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001975 Sema::AbstractParamType,
1976 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001977 }
1978
1979 return Invalid;
1980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Anders Carlssone65a3c82009-03-24 17:23:42 +00001982 bool VisitDecl(const Decl* D) {
1983 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1984 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Anders Carlssone65a3c82009-03-24 17:23:42 +00001986 return false;
1987 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001988 };
1989}
1990
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001991/// \brief Perform semantic checks on a class definition that has been
1992/// completing, introducing implicitly-declared members, checking for
1993/// abstract types, etc.
1994void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1995 if (!Record || Record->isInvalidDecl())
1996 return;
1997
Eli Friedmanff2d8782009-12-16 20:00:27 +00001998 if (!Record->isDependentType())
1999 AddImplicitlyDeclaredMembersToClass(Record);
2000
2001 if (Record->isInvalidDecl())
2002 return;
2003
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002004 if (!Record->isAbstract()) {
2005 // Collect all the pure virtual methods and see if this is an abstract
2006 // class after all.
2007 PureVirtualMethodCollector Collector(Context, Record);
2008 if (!Collector.empty())
2009 Record->setAbstract(true);
2010 }
2011
2012 if (Record->isAbstract())
2013 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002014}
2015
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002016void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002017 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002018 SourceLocation LBrac,
2019 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002020 if (!TagDecl)
2021 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Douglas Gregor42af25f2009-05-11 19:58:34 +00002023 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002024
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002025 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002026 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002027 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002028
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002029 CheckCompletedCXXClass(
2030 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002031}
2032
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002033/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2034/// special functions, such as the default constructor, copy
2035/// constructor, or destructor, to the given C++ class (C++
2036/// [special]p1). This routine can only be executed just before the
2037/// definition of the class is complete.
2038void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002039 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002040 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002041
Sebastian Redl465226e2009-05-27 22:11:52 +00002042 // FIXME: Implicit declarations have exception specifications, which are
2043 // the union of the specifications of the implicitly called functions.
2044
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002045 if (!ClassDecl->hasUserDeclaredConstructor()) {
2046 // C++ [class.ctor]p5:
2047 // A default constructor for a class X is a constructor of class X
2048 // that can be called without an argument. If there is no
2049 // user-declared constructor for class X, a default constructor is
2050 // implicitly declared. An implicitly-declared default constructor
2051 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002052 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002053 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002054 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002055 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002056 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002057 Context.getFunctionType(Context.VoidTy,
2058 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002059 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002060 /*isExplicit=*/false,
2061 /*isInline=*/true,
2062 /*isImplicitlyDeclared=*/true);
2063 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002064 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002065 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002066 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002067 }
2068
2069 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2070 // C++ [class.copy]p4:
2071 // If the class definition does not explicitly declare a copy
2072 // constructor, one is declared implicitly.
2073
2074 // C++ [class.copy]p5:
2075 // The implicitly-declared copy constructor for a class X will
2076 // have the form
2077 //
2078 // X::X(const X&)
2079 //
2080 // if
2081 bool HasConstCopyConstructor = true;
2082
2083 // -- each direct or virtual base class B of X has a copy
2084 // constructor whose first parameter is of type const B& or
2085 // const volatile B&, and
2086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2087 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2088 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002089 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002090 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002091 = BaseClassDecl->hasConstCopyConstructor(Context);
2092 }
2093
2094 // -- for all the nonstatic data members of X that are of a
2095 // class type M (or array thereof), each such class type
2096 // has a copy constructor whose first parameter is of type
2097 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002098 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2099 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002100 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002101 QualType FieldType = (*Field)->getType();
2102 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2103 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002104 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002105 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002106 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002107 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002108 = FieldClassDecl->hasConstCopyConstructor(Context);
2109 }
2110 }
2111
Sebastian Redl64b45f72009-01-05 20:52:13 +00002112 // Otherwise, the implicitly declared copy constructor will have
2113 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002114 //
2115 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002116 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002117 if (HasConstCopyConstructor)
2118 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002119 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002120
Sebastian Redl64b45f72009-01-05 20:52:13 +00002121 // An implicitly-declared copy constructor is an inline public
2122 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002123 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002124 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002125 CXXConstructorDecl *CopyConstructor
2126 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002127 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002128 Context.getFunctionType(Context.VoidTy,
2129 &ArgType, 1,
2130 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002131 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002132 /*isExplicit=*/false,
2133 /*isInline=*/true,
2134 /*isImplicitlyDeclared=*/true);
2135 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002136 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002137 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002138
2139 // Add the parameter to the constructor.
2140 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2141 ClassDecl->getLocation(),
2142 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002143 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002144 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002145 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002146 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002147 }
2148
Sebastian Redl64b45f72009-01-05 20:52:13 +00002149 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2150 // Note: The following rules are largely analoguous to the copy
2151 // constructor rules. Note that virtual bases are not taken into account
2152 // for determining the argument type of the operator. Note also that
2153 // operators taking an object instead of a reference are allowed.
2154 //
2155 // C++ [class.copy]p10:
2156 // If the class definition does not explicitly declare a copy
2157 // assignment operator, one is declared implicitly.
2158 // The implicitly-defined copy assignment operator for a class X
2159 // will have the form
2160 //
2161 // X& X::operator=(const X&)
2162 //
2163 // if
2164 bool HasConstCopyAssignment = true;
2165
2166 // -- each direct base class B of X has a copy assignment operator
2167 // whose parameter is of type const B&, const volatile B& or B,
2168 // and
2169 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2170 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002171 assert(!Base->getType()->isDependentType() &&
2172 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002173 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002174 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002175 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002176 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002177 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002178 }
2179
2180 // -- for all the nonstatic data members of X that are of a class
2181 // type M (or array thereof), each such class type has a copy
2182 // assignment operator whose parameter is of type const M&,
2183 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002184 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2185 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002186 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002187 QualType FieldType = (*Field)->getType();
2188 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2189 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002190 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002191 const CXXRecordDecl *FieldClassDecl
2192 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002193 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002194 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002195 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002196 }
2197 }
2198
2199 // Otherwise, the implicitly declared copy assignment operator will
2200 // have the form
2201 //
2202 // X& X::operator=(X&)
2203 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002204 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002205 if (HasConstCopyAssignment)
2206 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002207 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002208
2209 // An implicitly-declared copy assignment operator is an inline public
2210 // member of its class.
2211 DeclarationName Name =
2212 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2213 CXXMethodDecl *CopyAssignment =
2214 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2215 Context.getFunctionType(RetType, &ArgType, 1,
2216 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002217 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002218 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002219 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002220 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002221 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002222
2223 // Add the parameter to the operator.
2224 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2225 ClassDecl->getLocation(),
2226 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002227 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002228 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002229 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002230
2231 // Don't call addedAssignmentOperator. There is no way to distinguish an
2232 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002233 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002234 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002235 }
2236
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002237 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002238 // C++ [class.dtor]p2:
2239 // If a class has no user-declared destructor, a destructor is
2240 // declared implicitly. An implicitly-declared destructor is an
2241 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002243 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002244 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002245 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002246 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002247 Context.getFunctionType(Context.VoidTy,
2248 0, 0, false, 0),
2249 /*isInline=*/true,
2250 /*isImplicitlyDeclared=*/true);
2251 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002252 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002253 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002254 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002255
2256 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002257 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002258}
2259
Douglas Gregor6569d682009-05-27 23:11:45 +00002260void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002261 Decl *D = TemplateD.getAs<Decl>();
2262 if (!D)
2263 return;
2264
2265 TemplateParameterList *Params = 0;
2266 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2267 Params = Template->getTemplateParameters();
2268 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2269 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2270 Params = PartialSpec->getTemplateParameters();
2271 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002272 return;
2273
Douglas Gregor6569d682009-05-27 23:11:45 +00002274 for (TemplateParameterList::iterator Param = Params->begin(),
2275 ParamEnd = Params->end();
2276 Param != ParamEnd; ++Param) {
2277 NamedDecl *Named = cast<NamedDecl>(*Param);
2278 if (Named->getDeclName()) {
2279 S->AddDecl(DeclPtrTy::make(Named));
2280 IdResolver.AddDecl(Named);
2281 }
2282 }
2283}
2284
John McCall7a1dc562009-12-19 10:49:29 +00002285void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2286 if (!RecordD) return;
2287 AdjustDeclIfTemplate(RecordD);
2288 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2289 PushDeclContext(S, Record);
2290}
2291
2292void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2293 if (!RecordD) return;
2294 PopDeclContext();
2295}
2296
Douglas Gregor72b505b2008-12-16 21:30:33 +00002297/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2298/// parsing a top-level (non-nested) C++ class, and we are now
2299/// parsing those parts of the given Method declaration that could
2300/// not be parsed earlier (C++ [class.mem]p2), such as default
2301/// arguments. This action should enter the scope of the given
2302/// Method declaration as if we had just parsed the qualified method
2303/// name. However, it should not bring the parameters into scope;
2304/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002305void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002306}
2307
2308/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2309/// C++ method declaration. We're (re-)introducing the given
2310/// function parameter into scope for use in parsing later parts of
2311/// the method declaration. For example, we could see an
2312/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002313void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002314 if (!ParamD)
2315 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Chris Lattnerb28317a2009-03-28 19:18:32 +00002317 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002318
2319 // If this parameter has an unparsed default argument, clear it out
2320 // to make way for the parsed default argument.
2321 if (Param->hasUnparsedDefaultArg())
2322 Param->setDefaultArg(0);
2323
Chris Lattnerb28317a2009-03-28 19:18:32 +00002324 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002325 if (Param->getDeclName())
2326 IdResolver.AddDecl(Param);
2327}
2328
2329/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2330/// processing the delayed method declaration for Method. The method
2331/// declaration is now considered finished. There may be a separate
2332/// ActOnStartOfFunctionDef action later (not necessarily
2333/// immediately!) for this method, if it was also defined inside the
2334/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002335void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002336 if (!MethodD)
2337 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002339 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Chris Lattnerb28317a2009-03-28 19:18:32 +00002341 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002342
2343 // Now that we have our default arguments, check the constructor
2344 // again. It could produce additional diagnostics or affect whether
2345 // the class has implicitly-declared destructors, among other
2346 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002347 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2348 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002349
2350 // Check the default arguments, which we may have added.
2351 if (!Method->isInvalidDecl())
2352 CheckCXXDefaultArguments(Method);
2353}
2354
Douglas Gregor42a552f2008-11-05 20:51:48 +00002355/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002356/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002357/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002358/// emit diagnostics and set the invalid bit to true. In any case, the type
2359/// will be updated to reflect a well-formed type for the constructor and
2360/// returned.
2361QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2362 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002363 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002364
2365 // C++ [class.ctor]p3:
2366 // A constructor shall not be virtual (10.3) or static (9.4). A
2367 // constructor can be invoked for a const, volatile or const
2368 // volatile object. A constructor shall not be declared const,
2369 // volatile, or const volatile (9.3.2).
2370 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002371 if (!D.isInvalidType())
2372 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2373 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2374 << SourceRange(D.getIdentifierLoc());
2375 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002376 }
2377 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002378 if (!D.isInvalidType())
2379 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2380 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2381 << SourceRange(D.getIdentifierLoc());
2382 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002383 SC = FunctionDecl::None;
2384 }
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Chris Lattner65401802009-04-25 08:28:21 +00002386 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2387 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002388 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002389 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2390 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002391 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002392 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2393 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002394 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002395 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2396 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002397 }
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Douglas Gregor42a552f2008-11-05 20:51:48 +00002399 // Rebuild the function type "R" without any type qualifiers (in
2400 // case any of the errors above fired) and with "void" as the
2401 // return type, since constructors don't have return types. We
2402 // *always* have to do this, because GetTypeForDeclarator will
2403 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002404 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002405 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2406 Proto->getNumArgs(),
2407 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002408}
2409
Douglas Gregor72b505b2008-12-16 21:30:33 +00002410/// CheckConstructor - Checks a fully-formed constructor for
2411/// well-formedness, issuing any diagnostics required. Returns true if
2412/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002413void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002414 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002415 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2416 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002417 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002418
2419 // C++ [class.copy]p3:
2420 // A declaration of a constructor for a class X is ill-formed if
2421 // its first parameter is of type (optionally cv-qualified) X and
2422 // either there are no other parameters or else all other
2423 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002424 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002425 ((Constructor->getNumParams() == 1) ||
2426 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002427 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2428 Constructor->getTemplateSpecializationKind()
2429 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002430 QualType ParamType = Constructor->getParamDecl(0)->getType();
2431 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2432 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002433 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2434 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002435 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002436
2437 // FIXME: Rather that making the constructor invalid, we should endeavor
2438 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002439 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002440 }
2441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Douglas Gregor72b505b2008-12-16 21:30:33 +00002443 // Notify the class that we've added a constructor.
2444 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002445}
2446
Anders Carlsson37909802009-11-30 21:24:50 +00002447/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2448/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002449bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002450 CXXRecordDecl *RD = Destructor->getParent();
2451
2452 if (Destructor->isVirtual()) {
2453 SourceLocation Loc;
2454
2455 if (!Destructor->isImplicit())
2456 Loc = Destructor->getLocation();
2457 else
2458 Loc = RD->getLocation();
2459
2460 // If we have a virtual destructor, look up the deallocation function
2461 FunctionDecl *OperatorDelete = 0;
2462 DeclarationName Name =
2463 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002464 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002465 return true;
2466
2467 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002468 }
Anders Carlsson37909802009-11-30 21:24:50 +00002469
2470 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002471}
2472
Mike Stump1eb44332009-09-09 15:08:12 +00002473static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002474FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2475 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2476 FTI.ArgInfo[0].Param &&
2477 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2478}
2479
Douglas Gregor42a552f2008-11-05 20:51:48 +00002480/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2481/// the well-formednes of the destructor declarator @p D with type @p
2482/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002483/// emit diagnostics and set the declarator to invalid. Even if this happens,
2484/// will be updated to reflect a well-formed type for the destructor and
2485/// returned.
2486QualType Sema::CheckDestructorDeclarator(Declarator &D,
2487 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002488 // C++ [class.dtor]p1:
2489 // [...] A typedef-name that names a class is a class-name
2490 // (7.1.3); however, a typedef-name that names a class shall not
2491 // be used as the identifier in the declarator for a destructor
2492 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002493 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002494 if (isa<TypedefType>(DeclaratorType)) {
2495 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002496 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002497 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002498 }
2499
2500 // C++ [class.dtor]p2:
2501 // A destructor is used to destroy objects of its class type. A
2502 // destructor takes no parameters, and no return type can be
2503 // specified for it (not even void). The address of a destructor
2504 // shall not be taken. A destructor shall not be static. A
2505 // destructor can be invoked for a const, volatile or const
2506 // volatile object. A destructor shall not be declared const,
2507 // volatile or const volatile (9.3.2).
2508 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002509 if (!D.isInvalidType())
2510 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2511 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2512 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002513 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002514 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002515 }
Chris Lattner65401802009-04-25 08:28:21 +00002516 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002517 // Destructors don't have return types, but the parser will
2518 // happily parse something like:
2519 //
2520 // class X {
2521 // float ~X();
2522 // };
2523 //
2524 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002525 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2526 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2527 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002528 }
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Chris Lattner65401802009-04-25 08:28:21 +00002530 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2531 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002532 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002533 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2534 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002535 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002536 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2537 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002538 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002539 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2540 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002541 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002542 }
2543
2544 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002545 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002546 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2547
2548 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002549 FTI.freeArgs();
2550 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002551 }
2552
Mike Stump1eb44332009-09-09 15:08:12 +00002553 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002554 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002555 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002556 D.setInvalidType();
2557 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002558
2559 // Rebuild the function type "R" without any type qualifiers or
2560 // parameters (in case any of the errors above fired) and with
2561 // "void" as the return type, since destructors don't have return
2562 // types. We *always* have to do this, because GetTypeForDeclarator
2563 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002564 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002565}
2566
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002567/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2568/// well-formednes of the conversion function declarator @p D with
2569/// type @p R. If there are any errors in the declarator, this routine
2570/// will emit diagnostics and return true. Otherwise, it will return
2571/// false. Either way, the type @p R will be updated to reflect a
2572/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002573void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002574 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002575 // C++ [class.conv.fct]p1:
2576 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002577 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002578 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002579 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002580 if (!D.isInvalidType())
2581 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2582 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2583 << SourceRange(D.getIdentifierLoc());
2584 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002585 SC = FunctionDecl::None;
2586 }
Chris Lattner6e475012009-04-25 08:35:12 +00002587 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002588 // Conversion functions don't have return types, but the parser will
2589 // happily parse something like:
2590 //
2591 // class X {
2592 // float operator bool();
2593 // };
2594 //
2595 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002596 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2597 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2598 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002599 }
2600
2601 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002602 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002603 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2604
2605 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002606 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002607 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002608 }
2609
Mike Stump1eb44332009-09-09 15:08:12 +00002610 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002611 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002612 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002613 D.setInvalidType();
2614 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002615
2616 // C++ [class.conv.fct]p4:
2617 // The conversion-type-id shall not represent a function type nor
2618 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002619 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002620 if (ConvType->isArrayType()) {
2621 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2622 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002623 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002624 } else if (ConvType->isFunctionType()) {
2625 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2626 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002627 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002628 }
2629
2630 // Rebuild the function type "R" without any parameters (in case any
2631 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002632 // return type.
2633 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002634 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002635
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002636 // C++0x explicit conversion operators.
2637 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002638 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002639 diag::warn_explicit_conversion_functions)
2640 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002641}
2642
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002643/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2644/// the declaration of the given C++ conversion function. This routine
2645/// is responsible for recording the conversion function in the C++
2646/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002647Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002648 assert(Conversion && "Expected to receive a conversion function declaration");
2649
Douglas Gregor9d350972008-12-12 08:25:50 +00002650 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002651
2652 // Make sure we aren't redeclaring the conversion function.
2653 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002654
2655 // C++ [class.conv.fct]p1:
2656 // [...] A conversion function is never used to convert a
2657 // (possibly cv-qualified) object to the (possibly cv-qualified)
2658 // same object type (or a reference to it), to a (possibly
2659 // cv-qualified) base class of that type (or a reference to it),
2660 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002661 // FIXME: Suppress this warning if the conversion function ends up being a
2662 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002663 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002664 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002665 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002666 ConvType = ConvTypeRef->getPointeeType();
2667 if (ConvType->isRecordType()) {
2668 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2669 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002670 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002671 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002672 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002673 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002674 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002675 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002676 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002677 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002678 }
2679
Douglas Gregor70316a02008-12-26 15:00:45 +00002680 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002681 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002682 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002683 = Conversion->getDescribedFunctionTemplate())
2684 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002685 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2686 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002687 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002688 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002689 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002690 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002691 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002692 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002693
Chris Lattnerb28317a2009-03-28 19:18:32 +00002694 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002695}
2696
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002697//===----------------------------------------------------------------------===//
2698// Namespace Handling
2699//===----------------------------------------------------------------------===//
2700
2701/// ActOnStartNamespaceDef - This is called at the start of a namespace
2702/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002703Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2704 SourceLocation IdentLoc,
2705 IdentifierInfo *II,
2706 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002707 NamespaceDecl *Namespc =
2708 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2709 Namespc->setLBracLoc(LBrace);
2710
2711 Scope *DeclRegionScope = NamespcScope->getParent();
2712
2713 if (II) {
2714 // C++ [namespace.def]p2:
2715 // The identifier in an original-namespace-definition shall not have been
2716 // previously defined in the declarative region in which the
2717 // original-namespace-definition appears. The identifier in an
2718 // original-namespace-definition is the name of the namespace. Subsequently
2719 // in that declarative region, it is treated as an original-namespace-name.
2720
John McCallf36e02d2009-10-09 21:13:30 +00002721 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002722 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002723 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregor44b43212008-12-11 16:49:14 +00002725 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2726 // This is an extended namespace definition.
2727 // Attach this namespace decl to the chain of extended namespace
2728 // definitions.
2729 OrigNS->setNextNamespace(Namespc);
2730 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002731
Mike Stump1eb44332009-09-09 15:08:12 +00002732 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002733 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002734 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002735 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002736 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002737 } else if (PrevDecl) {
2738 // This is an invalid name redefinition.
2739 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2740 << Namespc->getDeclName();
2741 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2742 Namespc->setInvalidDecl();
2743 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002744 } else if (II->isStr("std") &&
2745 CurContext->getLookupContext()->isTranslationUnit()) {
2746 // This is the first "real" definition of the namespace "std", so update
2747 // our cache of the "std" namespace to point at this definition.
2748 if (StdNamespace) {
2749 // We had already defined a dummy namespace "std". Link this new
2750 // namespace definition to the dummy namespace "std".
2751 StdNamespace->setNextNamespace(Namespc);
2752 StdNamespace->setLocation(IdentLoc);
2753 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2754 }
2755
2756 // Make our StdNamespace cache point at the first real definition of the
2757 // "std" namespace.
2758 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002759 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002760
2761 PushOnScopeChains(Namespc, DeclRegionScope);
2762 } else {
John McCall9aeed322009-10-01 00:25:31 +00002763 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002764 assert(Namespc->isAnonymousNamespace());
2765 CurContext->addDecl(Namespc);
2766
2767 // Link the anonymous namespace into its parent.
2768 NamespaceDecl *PrevDecl;
2769 DeclContext *Parent = CurContext->getLookupContext();
2770 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2771 PrevDecl = TU->getAnonymousNamespace();
2772 TU->setAnonymousNamespace(Namespc);
2773 } else {
2774 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2775 PrevDecl = ND->getAnonymousNamespace();
2776 ND->setAnonymousNamespace(Namespc);
2777 }
2778
2779 // Link the anonymous namespace with its previous declaration.
2780 if (PrevDecl) {
2781 assert(PrevDecl->isAnonymousNamespace());
2782 assert(!PrevDecl->getNextNamespace());
2783 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2784 PrevDecl->setNextNamespace(Namespc);
2785 }
John McCall9aeed322009-10-01 00:25:31 +00002786
2787 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2788 // behaves as if it were replaced by
2789 // namespace unique { /* empty body */ }
2790 // using namespace unique;
2791 // namespace unique { namespace-body }
2792 // where all occurrences of 'unique' in a translation unit are
2793 // replaced by the same identifier and this identifier differs
2794 // from all other identifiers in the entire program.
2795
2796 // We just create the namespace with an empty name and then add an
2797 // implicit using declaration, just like the standard suggests.
2798 //
2799 // CodeGen enforces the "universally unique" aspect by giving all
2800 // declarations semantically contained within an anonymous
2801 // namespace internal linkage.
2802
John McCall5fdd7642009-12-16 02:06:49 +00002803 if (!PrevDecl) {
2804 UsingDirectiveDecl* UD
2805 = UsingDirectiveDecl::Create(Context, CurContext,
2806 /* 'using' */ LBrace,
2807 /* 'namespace' */ SourceLocation(),
2808 /* qualifier */ SourceRange(),
2809 /* NNS */ NULL,
2810 /* identifier */ SourceLocation(),
2811 Namespc,
2812 /* Ancestor */ CurContext);
2813 UD->setImplicit();
2814 CurContext->addDecl(UD);
2815 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002816 }
2817
2818 // Although we could have an invalid decl (i.e. the namespace name is a
2819 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002820 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2821 // for the namespace has the declarations that showed up in that particular
2822 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002823 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002824 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002825}
2826
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002827/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2828/// is a namespace alias, returns the namespace it points to.
2829static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2830 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2831 return AD->getNamespace();
2832 return dyn_cast_or_null<NamespaceDecl>(D);
2833}
2834
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002835/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2836/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002837void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2838 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002839 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2840 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2841 Namespc->setRBracLoc(RBrace);
2842 PopDeclContext();
2843}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002844
Chris Lattnerb28317a2009-03-28 19:18:32 +00002845Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2846 SourceLocation UsingLoc,
2847 SourceLocation NamespcLoc,
2848 const CXXScopeSpec &SS,
2849 SourceLocation IdentLoc,
2850 IdentifierInfo *NamespcName,
2851 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002852 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2853 assert(NamespcName && "Invalid NamespcName.");
2854 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002855 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002856
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002857 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002858
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002859 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002860 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2861 LookupParsedName(R, S, &SS);
2862 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002863 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002864
John McCallf36e02d2009-10-09 21:13:30 +00002865 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002866 NamedDecl *Named = R.getFoundDecl();
2867 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2868 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002869 // C++ [namespace.udir]p1:
2870 // A using-directive specifies that the names in the nominated
2871 // namespace can be used in the scope in which the
2872 // using-directive appears after the using-directive. During
2873 // unqualified name lookup (3.4.1), the names appear as if they
2874 // were declared in the nearest enclosing namespace which
2875 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002876 // namespace. [Note: in this context, "contains" means "contains
2877 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002878
2879 // Find enclosing context containing both using-directive and
2880 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002881 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002882 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2883 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2884 CommonAncestor = CommonAncestor->getParent();
2885
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002886 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002887 SS.getRange(),
2888 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002889 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002890 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002891 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002892 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002893 }
2894
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002895 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002896 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002897 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002898}
2899
2900void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2901 // If scope has associated entity, then using directive is at namespace
2902 // or translation unit scope. We add UsingDirectiveDecls, into
2903 // it's lookup structure.
2904 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002905 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002906 else
2907 // Otherwise it is block-sope. using-directives will affect lookup
2908 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002909 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002910}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002911
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002912
2913Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002914 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00002915 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002916 SourceLocation UsingLoc,
2917 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002918 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002919 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002920 bool IsTypeName,
2921 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002922 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Douglas Gregor12c118a2009-11-04 16:30:06 +00002924 switch (Name.getKind()) {
2925 case UnqualifiedId::IK_Identifier:
2926 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002927 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002928 case UnqualifiedId::IK_ConversionFunctionId:
2929 break;
2930
2931 case UnqualifiedId::IK_ConstructorName:
John McCall604e7f12009-12-08 07:46:18 +00002932 // C++0x inherited constructors.
2933 if (getLangOptions().CPlusPlus0x) break;
2934
Douglas Gregor12c118a2009-11-04 16:30:06 +00002935 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2936 << SS.getRange();
2937 return DeclPtrTy();
2938
2939 case UnqualifiedId::IK_DestructorName:
2940 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2941 << SS.getRange();
2942 return DeclPtrTy();
2943
2944 case UnqualifiedId::IK_TemplateId:
2945 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2946 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2947 return DeclPtrTy();
2948 }
2949
2950 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00002951 if (!TargetName)
2952 return DeclPtrTy();
2953
John McCall60fa3cf2009-12-11 02:10:03 +00002954 // Warn about using declarations.
2955 // TODO: store that the declaration was written without 'using' and
2956 // talk about access decls instead of using decls in the
2957 // diagnostics.
2958 if (!HasUsingKeyword) {
2959 UsingLoc = Name.getSourceRange().getBegin();
2960
2961 Diag(UsingLoc, diag::warn_access_decl_deprecated)
2962 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
2963 "using ");
2964 }
2965
John McCall9488ea12009-11-17 05:59:44 +00002966 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002967 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002968 TargetName, AttrList,
2969 /* IsInstantiation */ false,
2970 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00002971 if (UD)
2972 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Anders Carlssonc72160b2009-08-28 05:40:36 +00002974 return DeclPtrTy::make(UD);
2975}
2976
John McCall9f54ad42009-12-10 09:41:52 +00002977/// Determines whether to create a using shadow decl for a particular
2978/// decl, given the set of decls existing prior to this using lookup.
2979bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2980 const LookupResult &Previous) {
2981 // Diagnose finding a decl which is not from a base class of the
2982 // current class. We do this now because there are cases where this
2983 // function will silently decide not to build a shadow decl, which
2984 // will pre-empt further diagnostics.
2985 //
2986 // We don't need to do this in C++0x because we do the check once on
2987 // the qualifier.
2988 //
2989 // FIXME: diagnose the following if we care enough:
2990 // struct A { int foo; };
2991 // struct B : A { using A::foo; };
2992 // template <class T> struct C : A {};
2993 // template <class T> struct D : C<T> { using B::foo; } // <---
2994 // This is invalid (during instantiation) in C++03 because B::foo
2995 // resolves to the using decl in B, which is not a base class of D<T>.
2996 // We can't diagnose it immediately because C<T> is an unknown
2997 // specialization. The UsingShadowDecl in D<T> then points directly
2998 // to A::foo, which will look well-formed when we instantiate.
2999 // The right solution is to not collapse the shadow-decl chain.
3000 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3001 DeclContext *OrigDC = Orig->getDeclContext();
3002
3003 // Handle enums and anonymous structs.
3004 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3005 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3006 while (OrigRec->isAnonymousStructOrUnion())
3007 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3008
3009 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3010 if (OrigDC == CurContext) {
3011 Diag(Using->getLocation(),
3012 diag::err_using_decl_nested_name_specifier_is_current_class)
3013 << Using->getNestedNameRange();
3014 Diag(Orig->getLocation(), diag::note_using_decl_target);
3015 return true;
3016 }
3017
3018 Diag(Using->getNestedNameRange().getBegin(),
3019 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3020 << Using->getTargetNestedNameDecl()
3021 << cast<CXXRecordDecl>(CurContext)
3022 << Using->getNestedNameRange();
3023 Diag(Orig->getLocation(), diag::note_using_decl_target);
3024 return true;
3025 }
3026 }
3027
3028 if (Previous.empty()) return false;
3029
3030 NamedDecl *Target = Orig;
3031 if (isa<UsingShadowDecl>(Target))
3032 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3033
John McCalld7533ec2009-12-11 02:33:26 +00003034 // If the target happens to be one of the previous declarations, we
3035 // don't have a conflict.
3036 //
3037 // FIXME: but we might be increasing its access, in which case we
3038 // should redeclare it.
3039 NamedDecl *NonTag = 0, *Tag = 0;
3040 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3041 I != E; ++I) {
3042 NamedDecl *D = (*I)->getUnderlyingDecl();
3043 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3044 return false;
3045
3046 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3047 }
3048
John McCall9f54ad42009-12-10 09:41:52 +00003049 if (Target->isFunctionOrFunctionTemplate()) {
3050 FunctionDecl *FD;
3051 if (isa<FunctionTemplateDecl>(Target))
3052 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3053 else
3054 FD = cast<FunctionDecl>(Target);
3055
3056 NamedDecl *OldDecl = 0;
3057 switch (CheckOverload(FD, Previous, OldDecl)) {
3058 case Ovl_Overload:
3059 return false;
3060
3061 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003062 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003063 break;
3064
3065 // We found a decl with the exact signature.
3066 case Ovl_Match:
3067 if (isa<UsingShadowDecl>(OldDecl)) {
3068 // Silently ignore the possible conflict.
3069 return false;
3070 }
3071
3072 // If we're in a record, we want to hide the target, so we
3073 // return true (without a diagnostic) to tell the caller not to
3074 // build a shadow decl.
3075 if (CurContext->isRecord())
3076 return true;
3077
3078 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003079 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003080 break;
3081 }
3082
3083 Diag(Target->getLocation(), diag::note_using_decl_target);
3084 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3085 return true;
3086 }
3087
3088 // Target is not a function.
3089
John McCall9f54ad42009-12-10 09:41:52 +00003090 if (isa<TagDecl>(Target)) {
3091 // No conflict between a tag and a non-tag.
3092 if (!Tag) return false;
3093
John McCall41ce66f2009-12-10 19:51:03 +00003094 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003095 Diag(Target->getLocation(), diag::note_using_decl_target);
3096 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3097 return true;
3098 }
3099
3100 // No conflict between a tag and a non-tag.
3101 if (!NonTag) return false;
3102
John McCall41ce66f2009-12-10 19:51:03 +00003103 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003104 Diag(Target->getLocation(), diag::note_using_decl_target);
3105 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3106 return true;
3107}
3108
John McCall9488ea12009-11-17 05:59:44 +00003109/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003110UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003111 UsingDecl *UD,
3112 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003113
3114 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003115 NamedDecl *Target = Orig;
3116 if (isa<UsingShadowDecl>(Target)) {
3117 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3118 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003119 }
3120
3121 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003122 = UsingShadowDecl::Create(Context, CurContext,
3123 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003124 UD->addShadowDecl(Shadow);
3125
3126 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003127 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003128 else
John McCall604e7f12009-12-08 07:46:18 +00003129 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003130 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003131
John McCall604e7f12009-12-08 07:46:18 +00003132 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3133 Shadow->setInvalidDecl();
3134
John McCall9f54ad42009-12-10 09:41:52 +00003135 return Shadow;
3136}
John McCall604e7f12009-12-08 07:46:18 +00003137
John McCall9f54ad42009-12-10 09:41:52 +00003138/// Hides a using shadow declaration. This is required by the current
3139/// using-decl implementation when a resolvable using declaration in a
3140/// class is followed by a declaration which would hide or override
3141/// one or more of the using decl's targets; for example:
3142///
3143/// struct Base { void foo(int); };
3144/// struct Derived : Base {
3145/// using Base::foo;
3146/// void foo(int);
3147/// };
3148///
3149/// The governing language is C++03 [namespace.udecl]p12:
3150///
3151/// When a using-declaration brings names from a base class into a
3152/// derived class scope, member functions in the derived class
3153/// override and/or hide member functions with the same name and
3154/// parameter types in a base class (rather than conflicting).
3155///
3156/// There are two ways to implement this:
3157/// (1) optimistically create shadow decls when they're not hidden
3158/// by existing declarations, or
3159/// (2) don't create any shadow decls (or at least don't make them
3160/// visible) until we've fully parsed/instantiated the class.
3161/// The problem with (1) is that we might have to retroactively remove
3162/// a shadow decl, which requires several O(n) operations because the
3163/// decl structures are (very reasonably) not designed for removal.
3164/// (2) avoids this but is very fiddly and phase-dependent.
3165void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3166 // Remove it from the DeclContext...
3167 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003168
John McCall9f54ad42009-12-10 09:41:52 +00003169 // ...and the scope, if applicable...
3170 if (S) {
3171 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3172 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003173 }
3174
John McCall9f54ad42009-12-10 09:41:52 +00003175 // ...and the using decl.
3176 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3177
3178 // TODO: complain somehow if Shadow was used. It shouldn't
3179 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003180}
3181
John McCall7ba107a2009-11-18 02:36:19 +00003182/// Builds a using declaration.
3183///
3184/// \param IsInstantiation - Whether this call arises from an
3185/// instantiation of an unresolved using declaration. We treat
3186/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003187NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3188 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003189 const CXXScopeSpec &SS,
3190 SourceLocation IdentLoc,
3191 DeclarationName Name,
3192 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003193 bool IsInstantiation,
3194 bool IsTypeName,
3195 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003196 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3197 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003198
Anders Carlsson550b14b2009-08-28 05:49:21 +00003199 // FIXME: We ignore attributes for now.
3200 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003201
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003202 if (SS.isEmpty()) {
3203 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003204 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003205 }
Mike Stump1eb44332009-09-09 15:08:12 +00003206
John McCall9f54ad42009-12-10 09:41:52 +00003207 // Do the redeclaration lookup in the current scope.
3208 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3209 ForRedeclaration);
3210 Previous.setHideTags(false);
3211 if (S) {
3212 LookupName(Previous, S);
3213
3214 // It is really dumb that we have to do this.
3215 LookupResult::Filter F = Previous.makeFilter();
3216 while (F.hasNext()) {
3217 NamedDecl *D = F.next();
3218 if (!isDeclInScope(D, CurContext, S))
3219 F.erase();
3220 }
3221 F.done();
3222 } else {
3223 assert(IsInstantiation && "no scope in non-instantiation");
3224 assert(CurContext->isRecord() && "scope not record in instantiation");
3225 LookupQualifiedName(Previous, CurContext);
3226 }
3227
Mike Stump1eb44332009-09-09 15:08:12 +00003228 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003229 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3230
John McCall9f54ad42009-12-10 09:41:52 +00003231 // Check for invalid redeclarations.
3232 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3233 return 0;
3234
3235 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003236 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3237 return 0;
3238
John McCallaf8e6ed2009-11-12 03:15:40 +00003239 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003240 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003241 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003242 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003243 // FIXME: not all declaration name kinds are legal here
3244 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3245 UsingLoc, TypenameLoc,
3246 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003247 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003248 } else {
3249 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3250 UsingLoc, SS.getRange(), NNS,
3251 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003252 }
John McCalled976492009-12-04 22:46:56 +00003253 } else {
3254 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3255 SS.getRange(), UsingLoc, NNS, Name,
3256 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003257 }
John McCalled976492009-12-04 22:46:56 +00003258 D->setAccess(AS);
3259 CurContext->addDecl(D);
3260
3261 if (!LookupContext) return D;
3262 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003263
John McCall604e7f12009-12-08 07:46:18 +00003264 if (RequireCompleteDeclContext(SS)) {
3265 UD->setInvalidDecl();
3266 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003267 }
3268
John McCall604e7f12009-12-08 07:46:18 +00003269 // Look up the target name.
3270
John McCalla24dc2e2009-11-17 02:14:36 +00003271 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003272
John McCall604e7f12009-12-08 07:46:18 +00003273 // Unlike most lookups, we don't always want to hide tag
3274 // declarations: tag names are visible through the using declaration
3275 // even if hidden by ordinary names, *except* in a dependent context
3276 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003277 if (!IsInstantiation)
3278 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003279
John McCalla24dc2e2009-11-17 02:14:36 +00003280 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003281
John McCallf36e02d2009-10-09 21:13:30 +00003282 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003283 Diag(IdentLoc, diag::err_no_member)
3284 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003285 UD->setInvalidDecl();
3286 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003287 }
3288
John McCalled976492009-12-04 22:46:56 +00003289 if (R.isAmbiguous()) {
3290 UD->setInvalidDecl();
3291 return UD;
3292 }
Mike Stump1eb44332009-09-09 15:08:12 +00003293
John McCall7ba107a2009-11-18 02:36:19 +00003294 if (IsTypeName) {
3295 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003296 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003297 Diag(IdentLoc, diag::err_using_typename_non_type);
3298 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3299 Diag((*I)->getUnderlyingDecl()->getLocation(),
3300 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003301 UD->setInvalidDecl();
3302 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003303 }
3304 } else {
3305 // If we asked for a non-typename and we got a type, error out,
3306 // but only if this is an instantiation of an unresolved using
3307 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003308 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003309 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3310 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003311 UD->setInvalidDecl();
3312 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003313 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003314 }
3315
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003316 // C++0x N2914 [namespace.udecl]p6:
3317 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003318 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003319 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3320 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003321 UD->setInvalidDecl();
3322 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003323 }
Mike Stump1eb44332009-09-09 15:08:12 +00003324
John McCall9f54ad42009-12-10 09:41:52 +00003325 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3326 if (!CheckUsingShadowDecl(UD, *I, Previous))
3327 BuildUsingShadowDecl(S, UD, *I);
3328 }
John McCall9488ea12009-11-17 05:59:44 +00003329
3330 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003331}
3332
John McCall9f54ad42009-12-10 09:41:52 +00003333/// Checks that the given using declaration is not an invalid
3334/// redeclaration. Note that this is checking only for the using decl
3335/// itself, not for any ill-formedness among the UsingShadowDecls.
3336bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3337 bool isTypeName,
3338 const CXXScopeSpec &SS,
3339 SourceLocation NameLoc,
3340 const LookupResult &Prev) {
3341 // C++03 [namespace.udecl]p8:
3342 // C++0x [namespace.udecl]p10:
3343 // A using-declaration is a declaration and can therefore be used
3344 // repeatedly where (and only where) multiple declarations are
3345 // allowed.
3346 // That's only in file contexts.
3347 if (CurContext->getLookupContext()->isFileContext())
3348 return false;
3349
3350 NestedNameSpecifier *Qual
3351 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3352
3353 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3354 NamedDecl *D = *I;
3355
3356 bool DTypename;
3357 NestedNameSpecifier *DQual;
3358 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3359 DTypename = UD->isTypeName();
3360 DQual = UD->getTargetNestedNameDecl();
3361 } else if (UnresolvedUsingValueDecl *UD
3362 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3363 DTypename = false;
3364 DQual = UD->getTargetNestedNameSpecifier();
3365 } else if (UnresolvedUsingTypenameDecl *UD
3366 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3367 DTypename = true;
3368 DQual = UD->getTargetNestedNameSpecifier();
3369 } else continue;
3370
3371 // using decls differ if one says 'typename' and the other doesn't.
3372 // FIXME: non-dependent using decls?
3373 if (isTypeName != DTypename) continue;
3374
3375 // using decls differ if they name different scopes (but note that
3376 // template instantiation can cause this check to trigger when it
3377 // didn't before instantiation).
3378 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3379 Context.getCanonicalNestedNameSpecifier(DQual))
3380 continue;
3381
3382 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003383 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003384 return true;
3385 }
3386
3387 return false;
3388}
3389
John McCall604e7f12009-12-08 07:46:18 +00003390
John McCalled976492009-12-04 22:46:56 +00003391/// Checks that the given nested-name qualifier used in a using decl
3392/// in the current context is appropriately related to the current
3393/// scope. If an error is found, diagnoses it and returns true.
3394bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3395 const CXXScopeSpec &SS,
3396 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003397 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003398
John McCall604e7f12009-12-08 07:46:18 +00003399 if (!CurContext->isRecord()) {
3400 // C++03 [namespace.udecl]p3:
3401 // C++0x [namespace.udecl]p8:
3402 // A using-declaration for a class member shall be a member-declaration.
3403
3404 // If we weren't able to compute a valid scope, it must be a
3405 // dependent class scope.
3406 if (!NamedContext || NamedContext->isRecord()) {
3407 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3408 << SS.getRange();
3409 return true;
3410 }
3411
3412 // Otherwise, everything is known to be fine.
3413 return false;
3414 }
3415
3416 // The current scope is a record.
3417
3418 // If the named context is dependent, we can't decide much.
3419 if (!NamedContext) {
3420 // FIXME: in C++0x, we can diagnose if we can prove that the
3421 // nested-name-specifier does not refer to a base class, which is
3422 // still possible in some cases.
3423
3424 // Otherwise we have to conservatively report that things might be
3425 // okay.
3426 return false;
3427 }
3428
3429 if (!NamedContext->isRecord()) {
3430 // Ideally this would point at the last name in the specifier,
3431 // but we don't have that level of source info.
3432 Diag(SS.getRange().getBegin(),
3433 diag::err_using_decl_nested_name_specifier_is_not_class)
3434 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3435 return true;
3436 }
3437
3438 if (getLangOptions().CPlusPlus0x) {
3439 // C++0x [namespace.udecl]p3:
3440 // In a using-declaration used as a member-declaration, the
3441 // nested-name-specifier shall name a base class of the class
3442 // being defined.
3443
3444 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3445 cast<CXXRecordDecl>(NamedContext))) {
3446 if (CurContext == NamedContext) {
3447 Diag(NameLoc,
3448 diag::err_using_decl_nested_name_specifier_is_current_class)
3449 << SS.getRange();
3450 return true;
3451 }
3452
3453 Diag(SS.getRange().getBegin(),
3454 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3455 << (NestedNameSpecifier*) SS.getScopeRep()
3456 << cast<CXXRecordDecl>(CurContext)
3457 << SS.getRange();
3458 return true;
3459 }
3460
3461 return false;
3462 }
3463
3464 // C++03 [namespace.udecl]p4:
3465 // A using-declaration used as a member-declaration shall refer
3466 // to a member of a base class of the class being defined [etc.].
3467
3468 // Salient point: SS doesn't have to name a base class as long as
3469 // lookup only finds members from base classes. Therefore we can
3470 // diagnose here only if we can prove that that can't happen,
3471 // i.e. if the class hierarchies provably don't intersect.
3472
3473 // TODO: it would be nice if "definitely valid" results were cached
3474 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3475 // need to be repeated.
3476
3477 struct UserData {
3478 llvm::DenseSet<const CXXRecordDecl*> Bases;
3479
3480 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3481 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3482 Data->Bases.insert(Base);
3483 return true;
3484 }
3485
3486 bool hasDependentBases(const CXXRecordDecl *Class) {
3487 return !Class->forallBases(collect, this);
3488 }
3489
3490 /// Returns true if the base is dependent or is one of the
3491 /// accumulated base classes.
3492 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3493 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3494 return !Data->Bases.count(Base);
3495 }
3496
3497 bool mightShareBases(const CXXRecordDecl *Class) {
3498 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3499 }
3500 };
3501
3502 UserData Data;
3503
3504 // Returns false if we find a dependent base.
3505 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3506 return false;
3507
3508 // Returns false if the class has a dependent base or if it or one
3509 // of its bases is present in the base set of the current context.
3510 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3511 return false;
3512
3513 Diag(SS.getRange().getBegin(),
3514 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3515 << (NestedNameSpecifier*) SS.getScopeRep()
3516 << cast<CXXRecordDecl>(CurContext)
3517 << SS.getRange();
3518
3519 return true;
John McCalled976492009-12-04 22:46:56 +00003520}
3521
Mike Stump1eb44332009-09-09 15:08:12 +00003522Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003523 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003524 SourceLocation AliasLoc,
3525 IdentifierInfo *Alias,
3526 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003527 SourceLocation IdentLoc,
3528 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Anders Carlsson81c85c42009-03-28 23:53:49 +00003530 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003531 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3532 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003533
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003534 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003535 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003536 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003537 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003538 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003539 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003540 if (!R.isAmbiguous() && !R.empty() &&
3541 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003542 return DeclPtrTy();
3543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003545 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3546 diag::err_redefinition_different_kind;
3547 Diag(AliasLoc, DiagID) << Alias;
3548 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003549 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003550 }
3551
John McCalla24dc2e2009-11-17 02:14:36 +00003552 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003553 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003554
John McCallf36e02d2009-10-09 21:13:30 +00003555 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003556 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003557 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003558 }
Mike Stump1eb44332009-09-09 15:08:12 +00003559
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003560 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003561 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3562 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003563 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003564 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003566 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003567 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003568}
3569
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003570void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3571 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003572 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3573 !Constructor->isUsed()) &&
3574 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003575
Eli Friedman80c30da2009-11-09 19:20:36 +00003576 CXXRecordDecl *ClassDecl
3577 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3578 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003579
Eli Friedman80c30da2009-11-09 19:20:36 +00003580 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003581 Diag(CurrentLocation, diag::note_member_synthesized_at)
3582 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003583 Constructor->setInvalidDecl();
3584 } else {
3585 Constructor->setUsed();
3586 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003587}
3588
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003589void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003590 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003591 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3592 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003593 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003594 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3595 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003596 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003597 // implicitly defined, all the implicitly-declared default destructors
3598 // for its base class and its non-static data members shall have been
3599 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003600 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3601 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003602 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003603 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003604 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003605 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003606 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3607 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3608 else
Mike Stump1eb44332009-09-09 15:08:12 +00003609 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003610 "DefineImplicitDestructor - missing dtor in a base class");
3611 }
3612 }
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003614 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3615 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003616 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3617 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3618 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003619 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003620 CXXRecordDecl *FieldClassDecl
3621 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3622 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003623 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003624 const_cast<CXXDestructorDecl*>(
3625 FieldClassDecl->getDestructor(Context)))
3626 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3627 else
Mike Stump1eb44332009-09-09 15:08:12 +00003628 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003629 "DefineImplicitDestructor - missing dtor in class of a data member");
3630 }
3631 }
3632 }
Anders Carlsson37909802009-11-30 21:24:50 +00003633
3634 // FIXME: If CheckDestructor fails, we should emit a note about where the
3635 // implicit destructor was needed.
3636 if (CheckDestructor(Destructor)) {
3637 Diag(CurrentLocation, diag::note_member_synthesized_at)
3638 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3639
3640 Destructor->setInvalidDecl();
3641 return;
3642 }
3643
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003644 Destructor->setUsed();
3645}
3646
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003647void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3648 CXXMethodDecl *MethodDecl) {
3649 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3650 MethodDecl->getOverloadedOperator() == OO_Equal &&
3651 !MethodDecl->isUsed()) &&
3652 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003654 CXXRecordDecl *ClassDecl
3655 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003657 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003658 // Before the implicitly-declared copy assignment operator for a class is
3659 // implicitly defined, all implicitly-declared copy assignment operators
3660 // for its direct base classes and its nonstatic data members shall have
3661 // been implicitly defined.
3662 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003663 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3664 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003665 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003666 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003667 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003668 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3669 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003670 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3671 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003672 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3673 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003674 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3675 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3676 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003677 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003678 CXXRecordDecl *FieldClassDecl
3679 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003680 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003681 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3682 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003683 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003684 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003685 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003686 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3687 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003688 Diag(CurrentLocation, diag::note_first_required_here);
3689 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003690 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003691 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003692 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3693 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003694 Diag(CurrentLocation, diag::note_first_required_here);
3695 err = true;
3696 }
3697 }
3698 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003699 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003700}
3701
3702CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003703Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3704 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003705 CXXRecordDecl *ClassDecl) {
3706 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3707 QualType RHSType(LHSType);
3708 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003709 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003710 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003711 RHSType = Context.getCVRQualifiedType(RHSType,
3712 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003713 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003714 LHSType,
3715 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003716 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003717 RHSType,
3718 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003719 Expr *Args[2] = { &*LHS, &*RHS };
3720 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003721 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003722 CandidateSet);
3723 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003724 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003725 return cast<CXXMethodDecl>(Best->Function);
3726 assert(false &&
3727 "getAssignOperatorMethod - copy assignment operator method not found");
3728 return 0;
3729}
3730
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003731void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3732 CXXConstructorDecl *CopyConstructor,
3733 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003734 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003735 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003736 !CopyConstructor->isUsed()) &&
3737 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003739 CXXRecordDecl *ClassDecl
3740 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3741 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003742 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003743 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003744 // implicitly defined, all the implicitly-declared copy constructors
3745 // for its base class and its non-static data members shall have been
3746 // implicitly defined.
3747 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3748 Base != ClassDecl->bases_end(); ++Base) {
3749 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003750 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003751 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003752 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003753 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003754 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003755 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3756 FieldEnd = ClassDecl->field_end();
3757 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003758 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3759 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3760 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003761 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003762 CXXRecordDecl *FieldClassDecl
3763 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003764 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003765 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003766 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003767 }
3768 }
3769 CopyConstructor->setUsed();
3770}
3771
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003772Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003773Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003774 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003775 MultiExprArg ExprArgs,
3776 bool RequiresZeroInit) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003777 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Douglas Gregor39da0b82009-09-09 23:08:42 +00003779 // C++ [class.copy]p15:
3780 // Whenever a temporary class object is copied using a copy constructor, and
3781 // this object and the copy have the same cv-unqualified type, an
3782 // implementation is permitted to treat the original and the copy as two
3783 // different ways of referring to the same object and not perform a copy at
3784 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003786 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003787 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003788 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3790 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3791 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003792 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3793 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003794 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3795 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003796 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3797 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3798 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003799
3800 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3801 Elidable = !CE->getCallReturnType()->isReferenceType();
3802 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003803 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003804 else if (isa<CXXConstructExpr>(E))
3805 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
3808 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003809 Elidable, move(ExprArgs), RequiresZeroInit);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003810}
3811
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003812/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3813/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003814Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003815Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3816 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003817 MultiExprArg ExprArgs,
3818 bool RequiresZeroInit) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003819 unsigned NumExprs = ExprArgs.size();
3820 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Douglas Gregor7edfb692009-11-23 12:27:39 +00003822 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003823 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003824 Constructor, Elidable, Exprs, NumExprs,
3825 RequiresZeroInit));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003826}
3827
Anders Carlssone7624a72009-08-27 05:08:22 +00003828Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003829Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3830 QualType Ty,
3831 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003832 MultiExprArg Args,
3833 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003834 unsigned NumExprs = Args.size();
3835 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003836
Douglas Gregor7edfb692009-11-23 12:27:39 +00003837 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003838 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3839 TyBeginLoc, Exprs,
3840 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003841}
3842
3843
Mike Stump1eb44332009-09-09 15:08:12 +00003844bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003845 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003846 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003847 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003848 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003849 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003850 if (TempResult.isInvalid())
3851 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003853 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003854 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003855 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor78d15832009-05-26 18:54:04 +00003856 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Anders Carlssonfe2de492009-08-25 05:18:00 +00003858 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003859}
3860
Mike Stump1eb44332009-09-09 15:08:12 +00003861void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003862 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003863 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003864 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003865 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003866 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003867 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003868}
3869
Mike Stump1eb44332009-09-09 15:08:12 +00003870/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003871/// ActOnDeclarator, when a C++ direct initializer is present.
3872/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003873void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3874 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003875 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003876 SourceLocation *CommaLocs,
3877 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00003878 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003879 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003880
3881 // If there is no declaration, there was an error parsing it. Just ignore
3882 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003883 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003886 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3887 if (!VDecl) {
3888 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3889 RealDecl->setInvalidDecl();
3890 return;
3891 }
3892
Douglas Gregor83ddad32009-08-26 21:14:46 +00003893 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003894 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003895 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3896 //
3897 // Clients that want to distinguish between the two forms, can check for
3898 // direct initializer using VarDecl::hasCXXDirectInitializer().
3899 // A major benefit is that clients that don't particularly care about which
3900 // exactly form was it (like the CodeGen) can handle both cases without
3901 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003902
Douglas Gregor83ddad32009-08-26 21:14:46 +00003903 // If either the declaration has a dependent type or if any of the expressions
3904 // is type-dependent, we represent the initialization via a ParenListExpr for
3905 // later use during template instantiation.
3906 if (VDecl->getType()->isDependentType() ||
3907 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3908 // Let clients know that initialization was done with a direct initializer.
3909 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003910
Douglas Gregor83ddad32009-08-26 21:14:46 +00003911 // Store the initialization expressions as a ParenListExpr.
3912 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003913 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003914 new (Context) ParenListExpr(Context, LParenLoc,
3915 (Expr **)Exprs.release(),
3916 NumExprs, RParenLoc));
3917 return;
3918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Douglas Gregor83ddad32009-08-26 21:14:46 +00003920
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003921 // C++ 8.5p11:
3922 // The form of initialization (using parentheses or '=') is generally
3923 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003924 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003925 QualType DeclInitType = VDecl->getType();
3926 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003927 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003928
Douglas Gregor615c5d42009-03-24 16:43:20 +00003929 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3930 diag::err_typecheck_decl_incomplete_type)) {
3931 VDecl->setInvalidDecl();
3932 return;
3933 }
3934
Douglas Gregor90f93822009-12-22 22:17:25 +00003935 // The variable can not have an abstract class type.
3936 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3937 diag::err_abstract_type_in_decl,
3938 AbstractVariableType))
3939 VDecl->setInvalidDecl();
3940
3941 const VarDecl *Def = 0;
3942 if (VDecl->getDefinition(Def)) {
3943 Diag(VDecl->getLocation(), diag::err_redefinition)
3944 << VDecl->getDeclName();
3945 Diag(Def->getLocation(), diag::note_previous_definition);
3946 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003947 return;
3948 }
Douglas Gregor90f93822009-12-22 22:17:25 +00003949
3950 // Capture the variable that is being initialized and the style of
3951 // initialization.
3952 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3953
3954 // FIXME: Poor source location information.
3955 InitializationKind Kind
3956 = InitializationKind::CreateDirect(VDecl->getLocation(),
3957 LParenLoc, RParenLoc);
3958
3959 InitializationSequence InitSeq(*this, Entity, Kind,
3960 (Expr**)Exprs.get(), Exprs.size());
3961 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
3962 if (Result.isInvalid()) {
3963 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003964 return;
3965 }
Douglas Gregor90f93822009-12-22 22:17:25 +00003966
3967 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
3968 VDecl->setInit(Context, Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003969 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003970
Douglas Gregor90f93822009-12-22 22:17:25 +00003971 if (VDecl->getType()->getAs<RecordType>())
3972 FinalizeVarWithDestructor(VDecl, DeclInitType);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003973}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003974
Douglas Gregor19aeac62009-11-14 03:27:21 +00003975/// \brief Add the applicable constructor candidates for an initialization
3976/// by constructor.
3977static void AddConstructorInitializationCandidates(Sema &SemaRef,
3978 QualType ClassType,
3979 Expr **Args,
3980 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00003981 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003982 OverloadCandidateSet &CandidateSet) {
3983 // C++ [dcl.init]p14:
3984 // If the initialization is direct-initialization, or if it is
3985 // copy-initialization where the cv-unqualified version of the
3986 // source type is the same class as, or a derived class of, the
3987 // class of the destination, constructors are considered. The
3988 // applicable constructors are enumerated (13.3.1.3), and the
3989 // best one is chosen through overload resolution (13.3). The
3990 // constructor so selected is called to initialize the object,
3991 // with the initializer expression(s) as its argument(s). If no
3992 // constructor applies, or the overload resolution is ambiguous,
3993 // the initialization is ill-formed.
3994 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3995 assert(ClassRec && "Can only initialize a class type here");
3996
3997 // FIXME: When we decide not to synthesize the implicitly-declared
3998 // constructors, we'll need to make them appear here.
3999
4000 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4001 DeclarationName ConstructorName
4002 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4003 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4004 DeclContext::lookup_const_iterator Con, ConEnd;
4005 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4006 Con != ConEnd; ++Con) {
4007 // Find the constructor (which may be a template).
4008 CXXConstructorDecl *Constructor = 0;
4009 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4010 if (ConstructorTmpl)
4011 Constructor
4012 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4013 else
4014 Constructor = cast<CXXConstructorDecl>(*Con);
4015
Douglas Gregor20093b42009-12-09 23:02:17 +00004016 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4017 (Kind.getKind() == InitializationKind::IK_Value) ||
4018 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004019 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004020 ((Kind.getKind() == InitializationKind::IK_Default) &&
4021 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004022 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004023 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4024 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004025 Args, NumArgs, CandidateSet);
4026 else
4027 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
4028 }
4029 }
4030}
4031
4032/// \brief Attempt to perform initialization by constructor
4033/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4034/// copy-initialization.
4035///
4036/// This routine determines whether initialization by constructor is possible,
4037/// but it does not emit any diagnostics in the case where the initialization
4038/// is ill-formed.
4039///
4040/// \param ClassType the type of the object being initialized, which must have
4041/// class type.
4042///
4043/// \param Args the arguments provided to initialize the object
4044///
4045/// \param NumArgs the number of arguments provided to initialize the object
4046///
4047/// \param Kind the type of initialization being performed
4048///
4049/// \returns the constructor used to initialize the object, if successful.
4050/// Otherwise, emits a diagnostic and returns NULL.
4051CXXConstructorDecl *
4052Sema::TryInitializationByConstructor(QualType ClassType,
4053 Expr **Args, unsigned NumArgs,
4054 SourceLocation Loc,
4055 InitializationKind Kind) {
4056 // Build the overload candidate set
4057 OverloadCandidateSet CandidateSet;
4058 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4059 CandidateSet);
4060
4061 // Determine whether we found a constructor we can use.
4062 OverloadCandidateSet::iterator Best;
4063 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4064 case OR_Success:
4065 case OR_Deleted:
4066 // We found a constructor. Return it.
4067 return cast<CXXConstructorDecl>(Best->Function);
4068
4069 case OR_No_Viable_Function:
4070 case OR_Ambiguous:
4071 // Overload resolution failed. Return nothing.
4072 return 0;
4073 }
4074
4075 // Silence GCC warning
4076 return 0;
4077}
4078
Douglas Gregor39da0b82009-09-09 23:08:42 +00004079/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4080/// may occur as part of direct-initialization or copy-initialization.
4081///
4082/// \param ClassType the type of the object being initialized, which must have
4083/// class type.
4084///
4085/// \param ArgsPtr the arguments provided to initialize the object
4086///
4087/// \param Loc the source location where the initialization occurs
4088///
4089/// \param Range the source range that covers the entire initialization
4090///
4091/// \param InitEntity the name of the entity being initialized, if known
4092///
4093/// \param Kind the type of initialization being performed
4094///
4095/// \param ConvertedArgs a vector that will be filled in with the
4096/// appropriately-converted arguments to the constructor (if initialization
4097/// succeeded).
4098///
4099/// \returns the constructor used to initialize the object, if successful.
4100/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004101CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004102Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004103 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004104 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004105 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004106 InitializationKind Kind,
4107 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004108
4109 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004110 Expr **Args = (Expr **)ArgsPtr.get();
4111 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004112 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004113 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4114 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004115
Douglas Gregor18fe5682008-11-03 20:45:27 +00004116 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004117 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004118 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004119 // We found a constructor. Break out so that we can convert the arguments
4120 // appropriately.
4121 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Douglas Gregor18fe5682008-11-03 20:45:27 +00004123 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004124 if (InitEntity)
4125 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004126 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004127 else
4128 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004129 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00004130 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004131 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Douglas Gregor18fe5682008-11-03 20:45:27 +00004133 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004134 if (InitEntity)
4135 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4136 else
4137 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004138 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4139 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004140
4141 case OR_Deleted:
4142 if (InitEntity)
4143 Diag(Loc, diag::err_ovl_deleted_init)
4144 << Best->Function->isDeleted()
4145 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004146 else {
4147 const CXXRecordDecl *RD =
4148 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004149 Diag(Loc, diag::err_ovl_deleted_init)
4150 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004151 << RD->getDeclName() << Range;
4152 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004153 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4154 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004155 }
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Douglas Gregor39da0b82009-09-09 23:08:42 +00004157 // Convert the arguments, fill in default arguments, etc.
4158 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4159 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4160 return 0;
4161
4162 return Constructor;
4163}
4164
4165/// \brief Given a constructor and the set of arguments provided for the
4166/// constructor, convert the arguments and add any required default arguments
4167/// to form a proper call to this constructor.
4168///
4169/// \returns true if an error occurred, false otherwise.
4170bool
4171Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4172 MultiExprArg ArgsPtr,
4173 SourceLocation Loc,
4174 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4175 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4176 unsigned NumArgs = ArgsPtr.size();
4177 Expr **Args = (Expr **)ArgsPtr.get();
4178
4179 const FunctionProtoType *Proto
4180 = Constructor->getType()->getAs<FunctionProtoType>();
4181 assert(Proto && "Constructor without a prototype?");
4182 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004183
4184 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004185 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004186 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004187 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004188 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004189
4190 VariadicCallType CallType =
4191 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4192 llvm::SmallVector<Expr *, 8> AllArgs;
4193 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4194 Proto, 0, Args, NumArgs, AllArgs,
4195 CallType);
4196 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4197 ConvertedArgs.push_back(AllArgs[i]);
4198 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004199}
4200
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004201/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4202/// determine whether they are reference-related,
4203/// reference-compatible, reference-compatible with added
4204/// qualification, or incompatible, for use in C++ initialization by
4205/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4206/// type, and the first type (T1) is the pointee type of the reference
4207/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004208Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004209Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004210 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004211 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004212 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004213 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004214 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004215
Douglas Gregor393896f2009-11-05 13:06:35 +00004216 QualType T1 = Context.getCanonicalType(OrigT1);
4217 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004218 Qualifiers T1Quals, T2Quals;
4219 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4220 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004221
4222 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004223 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004224 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004225 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004226 if (UnqualT1 == UnqualT2)
4227 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004228 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4229 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4230 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004231 DerivedToBase = true;
4232 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004233 return Ref_Incompatible;
4234
4235 // At this point, we know that T1 and T2 are reference-related (at
4236 // least).
4237
Chandler Carruth28e318c2009-12-29 07:16:59 +00004238 // If the type is an array type, promote the element qualifiers to the type
4239 // for comparison.
4240 if (isa<ArrayType>(T1) && T1Quals)
4241 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4242 if (isa<ArrayType>(T2) && T2Quals)
4243 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4244
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004245 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004246 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004247 // reference-related to T2 and cv1 is the same cv-qualification
4248 // as, or greater cv-qualification than, cv2. For purposes of
4249 // overload resolution, cases for which cv1 is greater
4250 // cv-qualification than cv2 are identified as
4251 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004252 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004253 return Ref_Compatible;
4254 else if (T1.isMoreQualifiedThan(T2))
4255 return Ref_Compatible_With_Added_Qualification;
4256 else
4257 return Ref_Related;
4258}
4259
4260/// CheckReferenceInit - Check the initialization of a reference
4261/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4262/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004263/// list), and DeclType is the type of the declaration. When ICS is
4264/// non-null, this routine will compute the implicit conversion
4265/// sequence according to C++ [over.ics.ref] and will not produce any
4266/// diagnostics; when ICS is null, it will emit diagnostics when any
4267/// errors are found. Either way, a return value of true indicates
4268/// that there was a failure, a return value of false indicates that
4269/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004270///
4271/// When @p SuppressUserConversions, user-defined conversions are
4272/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004273/// When @p AllowExplicit, we also permit explicit user-defined
4274/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004275/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004276/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4277/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004278bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004279Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004280 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004281 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004282 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004283 ImplicitConversionSequence *ICS,
4284 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004285 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4286
Ted Kremenek6217b802009-07-29 21:53:49 +00004287 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004288 QualType T2 = Init->getType();
4289
Douglas Gregor904eed32008-11-10 20:40:00 +00004290 // If the initializer is the address of an overloaded function, try
4291 // to resolve the overloaded function. If all goes well, T2 is the
4292 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004293 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004294 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004295 ICS != 0);
4296 if (Fn) {
4297 // Since we're performing this reference-initialization for
4298 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004299 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004300 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004301 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004302
Anders Carlsson96ad5332009-10-21 17:16:23 +00004303 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004304 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004305
4306 T2 = Fn->getType();
4307 }
4308 }
4309
Douglas Gregor15da57e2008-10-29 02:00:59 +00004310 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004311 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004312 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004313 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4314 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004315 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004316 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004317
4318 // Most paths end in a failed conversion.
4319 if (ICS)
4320 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004321
4322 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004323 // A reference to type "cv1 T1" is initialized by an expression
4324 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004325
4326 // -- If the initializer expression
4327
Sebastian Redla9845802009-03-29 15:27:50 +00004328 // Rvalue references cannot bind to lvalues (N2812).
4329 // There is absolutely no situation where they can. In particular, note that
4330 // this is ill-formed, even if B has a user-defined conversion to A&&:
4331 // B b;
4332 // A&& r = b;
4333 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4334 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004335 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004336 << Init->getSourceRange();
4337 return true;
4338 }
4339
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004340 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004341 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4342 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004343 //
4344 // Note that the bit-field check is skipped if we are just computing
4345 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004346 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004347 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004348 BindsDirectly = true;
4349
Douglas Gregor15da57e2008-10-29 02:00:59 +00004350 if (ICS) {
4351 // C++ [over.ics.ref]p1:
4352 // When a parameter of reference type binds directly (8.5.3)
4353 // to an argument expression, the implicit conversion sequence
4354 // is the identity conversion, unless the argument expression
4355 // has a type that is a derived class of the parameter type,
4356 // in which case the implicit conversion sequence is a
4357 // derived-to-base Conversion (13.3.3.1).
4358 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4359 ICS->Standard.First = ICK_Identity;
4360 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4361 ICS->Standard.Third = ICK_Identity;
4362 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4363 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004364 ICS->Standard.ReferenceBinding = true;
4365 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004366 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004367 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004368
4369 // Nothing more to do: the inaccessibility/ambiguity check for
4370 // derived-to-base conversions is suppressed when we're
4371 // computing the implicit conversion sequence (C++
4372 // [over.best.ics]p2).
4373 return false;
4374 } else {
4375 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004376 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4377 if (DerivedToBase)
4378 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004379 else if(CheckExceptionSpecCompatibility(Init, T1))
4380 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004381 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004382 }
4383 }
4384
4385 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004386 // implicitly converted to an lvalue of type "cv3 T3,"
4387 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004388 // 92) (this conversion is selected by enumerating the
4389 // applicable conversion functions (13.3.1.6) and choosing
4390 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004391 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004392 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004393 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004394 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004395
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004396 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00004397 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004398 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00004399 for (UnresolvedSet::iterator I = Conversions->begin(),
4400 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004401 NamedDecl *D = *I;
4402 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4403 if (isa<UsingShadowDecl>(D))
4404 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4405
Mike Stump1eb44332009-09-09 15:08:12 +00004406 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004407 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004408 CXXConversionDecl *Conv;
4409 if (ConvTemplate)
4410 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4411 else
John McCall701c89e2009-12-03 04:06:58 +00004412 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004413
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004414 // If the conversion function doesn't return a reference type,
4415 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004416 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004417 (AllowExplicit || !Conv->isExplicit())) {
4418 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00004419 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4420 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004421 else
John McCall701c89e2009-12-03 04:06:58 +00004422 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004423 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004424 }
4425
4426 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004427 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004428 case OR_Success:
4429 // This is a direct binding.
4430 BindsDirectly = true;
4431
4432 if (ICS) {
4433 // C++ [over.ics.ref]p1:
4434 //
4435 // [...] If the parameter binds directly to the result of
4436 // applying a conversion function to the argument
4437 // expression, the implicit conversion sequence is a
4438 // user-defined conversion sequence (13.3.3.1.2), with the
4439 // second standard conversion sequence either an identity
4440 // conversion or, if the conversion function returns an
4441 // entity of a type that is a derived class of the parameter
4442 // type, a derived-to-base Conversion.
4443 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4444 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4445 ICS->UserDefined.After = Best->FinalConversion;
4446 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004447 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004448 assert(ICS->UserDefined.After.ReferenceBinding &&
4449 ICS->UserDefined.After.DirectBinding &&
4450 "Expected a direct reference binding!");
4451 return false;
4452 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004453 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004454 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004455 CastExpr::CK_UserDefinedConversion,
4456 cast<CXXMethodDecl>(Best->Function),
4457 Owned(Init));
4458 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004459
4460 if (CheckExceptionSpecCompatibility(Init, T1))
4461 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004462 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4463 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004464 }
4465 break;
4466
4467 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004468 if (ICS) {
4469 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4470 Cand != CandidateSet.end(); ++Cand)
4471 if (Cand->Viable)
4472 ICS->ConversionFunctionSet.push_back(Cand->Function);
4473 break;
4474 }
4475 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4476 << Init->getSourceRange();
4477 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004478 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004479
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004480 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004481 case OR_Deleted:
4482 // There was no suitable conversion, or we found a deleted
4483 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004484 break;
4485 }
4486 }
Mike Stump1eb44332009-09-09 15:08:12 +00004487
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004488 if (BindsDirectly) {
4489 // C++ [dcl.init.ref]p4:
4490 // [...] In all cases where the reference-related or
4491 // reference-compatible relationship of two types is used to
4492 // establish the validity of a reference binding, and T1 is a
4493 // base class of T2, a program that necessitates such a binding
4494 // is ill-formed if T1 is an inaccessible (clause 11) or
4495 // ambiguous (10.2) base class of T2.
4496 //
4497 // Note that we only check this condition when we're allowed to
4498 // complain about errors, because we should not be checking for
4499 // ambiguity (or inaccessibility) unless the reference binding
4500 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004501 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004502 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004503 Init->getSourceRange(),
4504 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004505 else
4506 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004507 }
4508
4509 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004510 // type (i.e., cv1 shall be const), or the reference shall be an
4511 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004512 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004513 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004514 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004515 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004516 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004517 return true;
4518 }
4519
4520 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004521 // class type, and "cv1 T1" is reference-compatible with
4522 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004523 // following ways (the choice is implementation-defined):
4524 //
4525 // -- The reference is bound to the object represented by
4526 // the rvalue (see 3.10) or to a sub-object within that
4527 // object.
4528 //
Eli Friedman33a31382009-08-05 19:21:58 +00004529 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004530 // a constructor is called to copy the entire rvalue
4531 // object into the temporary. The reference is bound to
4532 // the temporary or to a sub-object within the
4533 // temporary.
4534 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004535 // The constructor that would be used to make the copy
4536 // shall be callable whether or not the copy is actually
4537 // done.
4538 //
Sebastian Redla9845802009-03-29 15:27:50 +00004539 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004540 // freedom, so we will always take the first option and never build
4541 // a temporary in this case. FIXME: We will, however, have to check
4542 // for the presence of a copy constructor in C++98/03 mode.
4543 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004544 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4545 if (ICS) {
4546 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4547 ICS->Standard.First = ICK_Identity;
4548 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4549 ICS->Standard.Third = ICK_Identity;
4550 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4551 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004552 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004553 ICS->Standard.DirectBinding = false;
4554 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004555 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004556 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004557 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4558 if (DerivedToBase)
4559 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004560 else if(CheckExceptionSpecCompatibility(Init, T1))
4561 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004562 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004563 }
4564 return false;
4565 }
4566
Eli Friedman33a31382009-08-05 19:21:58 +00004567 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004568 // initialized from the initializer expression using the
4569 // rules for a non-reference copy initialization (8.5). The
4570 // reference is then bound to the temporary. If T1 is
4571 // reference-related to T2, cv1 must be the same
4572 // cv-qualification as, or greater cv-qualification than,
4573 // cv2; otherwise, the program is ill-formed.
4574 if (RefRelationship == Ref_Related) {
4575 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4576 // we would be reference-compatible or reference-compatible with
4577 // added qualification. But that wasn't the case, so the reference
4578 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004579 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004580 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004581 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004582 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004583 return true;
4584 }
4585
Douglas Gregor734d9862009-01-30 23:27:23 +00004586 // If at least one of the types is a class type, the types are not
4587 // related, and we aren't allowed any user conversions, the
4588 // reference binding fails. This case is important for breaking
4589 // recursion, since TryImplicitConversion below will attempt to
4590 // create a temporary through the use of a copy constructor.
4591 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4592 (T1->isRecordType() || T2->isRecordType())) {
4593 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004594 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004595 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004596 return true;
4597 }
4598
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004599 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004600 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004601 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004602 //
Sebastian Redla9845802009-03-29 15:27:50 +00004603 // When a parameter of reference type is not bound directly to
4604 // an argument expression, the conversion sequence is the one
4605 // required to convert the argument expression to the
4606 // underlying type of the reference according to
4607 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4608 // to copy-initializing a temporary of the underlying type with
4609 // the argument expression. Any difference in top-level
4610 // cv-qualification is subsumed by the initialization itself
4611 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004612 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4613 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004614 /*ForceRValue=*/false,
4615 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004616
Sebastian Redla9845802009-03-29 15:27:50 +00004617 // Of course, that's still a reference binding.
4618 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4619 ICS->Standard.ReferenceBinding = true;
4620 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004621 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004622 ImplicitConversionSequence::UserDefinedConversion) {
4623 ICS->UserDefined.After.ReferenceBinding = true;
4624 ICS->UserDefined.After.RRefBinding = isRValRef;
4625 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004626 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4627 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004628 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004629 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004630 false, false,
4631 Conversions);
4632 if (badConversion) {
4633 if ((Conversions.ConversionKind ==
4634 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004635 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004636 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004637 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4638 for (int j = Conversions.ConversionFunctionSet.size()-1;
4639 j >= 0; j--) {
4640 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4641 Diag(Func->getLocation(), diag::err_ovl_candidate);
4642 }
4643 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004644 else {
4645 if (isRValRef)
4646 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4647 << Init->getSourceRange();
4648 else
4649 Diag(DeclLoc, diag::err_invalid_initialization)
4650 << DeclType << Init->getType() << Init->getSourceRange();
4651 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004652 }
4653 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004654 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004655}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004656
Anders Carlsson20d45d22009-12-12 00:32:00 +00004657static inline bool
4658CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4659 const FunctionDecl *FnDecl) {
4660 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4661 if (isa<NamespaceDecl>(DC)) {
4662 return SemaRef.Diag(FnDecl->getLocation(),
4663 diag::err_operator_new_delete_declared_in_namespace)
4664 << FnDecl->getDeclName();
4665 }
4666
4667 if (isa<TranslationUnitDecl>(DC) &&
4668 FnDecl->getStorageClass() == FunctionDecl::Static) {
4669 return SemaRef.Diag(FnDecl->getLocation(),
4670 diag::err_operator_new_delete_declared_static)
4671 << FnDecl->getDeclName();
4672 }
4673
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004674 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004675}
4676
Anders Carlsson156c78e2009-12-13 17:53:43 +00004677static inline bool
4678CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4679 CanQualType ExpectedResultType,
4680 CanQualType ExpectedFirstParamType,
4681 unsigned DependentParamTypeDiag,
4682 unsigned InvalidParamTypeDiag) {
4683 QualType ResultType =
4684 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4685
4686 // Check that the result type is not dependent.
4687 if (ResultType->isDependentType())
4688 return SemaRef.Diag(FnDecl->getLocation(),
4689 diag::err_operator_new_delete_dependent_result_type)
4690 << FnDecl->getDeclName() << ExpectedResultType;
4691
4692 // Check that the result type is what we expect.
4693 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4694 return SemaRef.Diag(FnDecl->getLocation(),
4695 diag::err_operator_new_delete_invalid_result_type)
4696 << FnDecl->getDeclName() << ExpectedResultType;
4697
4698 // A function template must have at least 2 parameters.
4699 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4700 return SemaRef.Diag(FnDecl->getLocation(),
4701 diag::err_operator_new_delete_template_too_few_parameters)
4702 << FnDecl->getDeclName();
4703
4704 // The function decl must have at least 1 parameter.
4705 if (FnDecl->getNumParams() == 0)
4706 return SemaRef.Diag(FnDecl->getLocation(),
4707 diag::err_operator_new_delete_too_few_parameters)
4708 << FnDecl->getDeclName();
4709
4710 // Check the the first parameter type is not dependent.
4711 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4712 if (FirstParamType->isDependentType())
4713 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4714 << FnDecl->getDeclName() << ExpectedFirstParamType;
4715
4716 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004717 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004718 ExpectedFirstParamType)
4719 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4720 << FnDecl->getDeclName() << ExpectedFirstParamType;
4721
4722 return false;
4723}
4724
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004725static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004726CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004727 // C++ [basic.stc.dynamic.allocation]p1:
4728 // A program is ill-formed if an allocation function is declared in a
4729 // namespace scope other than global scope or declared static in global
4730 // scope.
4731 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4732 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004733
4734 CanQualType SizeTy =
4735 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4736
4737 // C++ [basic.stc.dynamic.allocation]p1:
4738 // The return type shall be void*. The first parameter shall have type
4739 // std::size_t.
4740 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4741 SizeTy,
4742 diag::err_operator_new_dependent_param_type,
4743 diag::err_operator_new_param_type))
4744 return true;
4745
4746 // C++ [basic.stc.dynamic.allocation]p1:
4747 // The first parameter shall not have an associated default argument.
4748 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004749 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004750 diag::err_operator_new_default_arg)
4751 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4752
4753 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004754}
4755
4756static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004757CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4758 // C++ [basic.stc.dynamic.deallocation]p1:
4759 // A program is ill-formed if deallocation functions are declared in a
4760 // namespace scope other than global scope or declared static in global
4761 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004762 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4763 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004764
4765 // C++ [basic.stc.dynamic.deallocation]p2:
4766 // Each deallocation function shall return void and its first parameter
4767 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004768 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4769 SemaRef.Context.VoidPtrTy,
4770 diag::err_operator_delete_dependent_param_type,
4771 diag::err_operator_delete_param_type))
4772 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004773
Anders Carlsson46991d62009-12-12 00:16:02 +00004774 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4775 if (FirstParamType->isDependentType())
4776 return SemaRef.Diag(FnDecl->getLocation(),
4777 diag::err_operator_delete_dependent_param_type)
4778 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4779
4780 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4781 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004782 return SemaRef.Diag(FnDecl->getLocation(),
4783 diag::err_operator_delete_param_type)
4784 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004785
4786 return false;
4787}
4788
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004789/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4790/// of this overloaded operator is well-formed. If so, returns false;
4791/// otherwise, emits appropriate diagnostics and returns true.
4792bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004793 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004794 "Expected an overloaded operator declaration");
4795
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004796 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4797
Mike Stump1eb44332009-09-09 15:08:12 +00004798 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004799 // The allocation and deallocation functions, operator new,
4800 // operator new[], operator delete and operator delete[], are
4801 // described completely in 3.7.3. The attributes and restrictions
4802 // found in the rest of this subclause do not apply to them unless
4803 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004804 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004805 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004806
Anders Carlssona3ccda52009-12-12 00:26:23 +00004807 if (Op == OO_New || Op == OO_Array_New)
4808 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004809
4810 // C++ [over.oper]p6:
4811 // An operator function shall either be a non-static member
4812 // function or be a non-member function and have at least one
4813 // parameter whose type is a class, a reference to a class, an
4814 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004815 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4816 if (MethodDecl->isStatic())
4817 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004818 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004819 } else {
4820 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004821 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4822 ParamEnd = FnDecl->param_end();
4823 Param != ParamEnd; ++Param) {
4824 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004825 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4826 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004827 ClassOrEnumParam = true;
4828 break;
4829 }
4830 }
4831
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004832 if (!ClassOrEnumParam)
4833 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004834 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004835 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004836 }
4837
4838 // C++ [over.oper]p8:
4839 // An operator function cannot have default arguments (8.3.6),
4840 // except where explicitly stated below.
4841 //
Mike Stump1eb44332009-09-09 15:08:12 +00004842 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004843 // (C++ [over.call]p1).
4844 if (Op != OO_Call) {
4845 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4846 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004847 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004848 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004849 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004850 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004851 }
4852 }
4853
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004854 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4855 { false, false, false }
4856#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4857 , { Unary, Binary, MemberOnly }
4858#include "clang/Basic/OperatorKinds.def"
4859 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004860
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004861 bool CanBeUnaryOperator = OperatorUses[Op][0];
4862 bool CanBeBinaryOperator = OperatorUses[Op][1];
4863 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004864
4865 // C++ [over.oper]p8:
4866 // [...] Operator functions cannot have more or fewer parameters
4867 // than the number required for the corresponding operator, as
4868 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004869 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004870 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004871 if (Op != OO_Call &&
4872 ((NumParams == 1 && !CanBeUnaryOperator) ||
4873 (NumParams == 2 && !CanBeBinaryOperator) ||
4874 (NumParams < 1) || (NumParams > 2))) {
4875 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004876 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004877 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004878 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004879 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004880 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004881 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004882 assert(CanBeBinaryOperator &&
4883 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004884 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004885 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004886
Chris Lattner416e46f2008-11-21 07:57:12 +00004887 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004888 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004889 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004890
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004891 // Overloaded operators other than operator() cannot be variadic.
4892 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004893 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004894 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004895 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004896 }
4897
4898 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004899 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4900 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004901 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004902 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004903 }
4904
4905 // C++ [over.inc]p1:
4906 // The user-defined function called operator++ implements the
4907 // prefix and postfix ++ operator. If this function is a member
4908 // function with no parameters, or a non-member function with one
4909 // parameter of class or enumeration type, it defines the prefix
4910 // increment operator ++ for objects of that type. If the function
4911 // is a member function with one parameter (which shall be of type
4912 // int) or a non-member function with two parameters (the second
4913 // of which shall be of type int), it defines the postfix
4914 // increment operator ++ for objects of that type.
4915 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4916 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4917 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004918 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004919 ParamIsInt = BT->getKind() == BuiltinType::Int;
4920
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004921 if (!ParamIsInt)
4922 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004923 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004924 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004925 }
4926
Sebastian Redl64b45f72009-01-05 20:52:13 +00004927 // Notify the class if it got an assignment operator.
4928 if (Op == OO_Equal) {
4929 // Would have returned earlier otherwise.
4930 assert(isa<CXXMethodDecl>(FnDecl) &&
4931 "Overloaded = not member, but not filtered.");
4932 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4933 Method->getParent()->addedAssignmentOperator(Context, Method);
4934 }
4935
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004936 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004937}
Chris Lattner5a003a42008-12-17 07:09:26 +00004938
Douglas Gregor074149e2009-01-05 19:45:36 +00004939/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4940/// linkage specification, including the language and (if present)
4941/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4942/// the location of the language string literal, which is provided
4943/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4944/// the '{' brace. Otherwise, this linkage specification does not
4945/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004946Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4947 SourceLocation ExternLoc,
4948 SourceLocation LangLoc,
4949 const char *Lang,
4950 unsigned StrSize,
4951 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004952 LinkageSpecDecl::LanguageIDs Language;
4953 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4954 Language = LinkageSpecDecl::lang_c;
4955 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4956 Language = LinkageSpecDecl::lang_cxx;
4957 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004958 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004959 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004960 }
Mike Stump1eb44332009-09-09 15:08:12 +00004961
Chris Lattnercc98eac2008-12-17 07:13:27 +00004962 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004963
Douglas Gregor074149e2009-01-05 19:45:36 +00004964 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004965 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004966 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004967 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004968 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004969 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004970}
4971
Douglas Gregor074149e2009-01-05 19:45:36 +00004972/// ActOnFinishLinkageSpecification - Completely the definition of
4973/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4974/// valid, it's the position of the closing '}' brace in a linkage
4975/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004976Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4977 DeclPtrTy LinkageSpec,
4978 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004979 if (LinkageSpec)
4980 PopDeclContext();
4981 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004982}
4983
Douglas Gregord308e622009-05-18 20:51:54 +00004984/// \brief Perform semantic analysis for the variable declaration that
4985/// occurs within a C++ catch clause, returning the newly-created
4986/// variable.
4987VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004988 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004989 IdentifierInfo *Name,
4990 SourceLocation Loc,
4991 SourceRange Range) {
4992 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004993
4994 // Arrays and functions decay.
4995 if (ExDeclType->isArrayType())
4996 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4997 else if (ExDeclType->isFunctionType())
4998 ExDeclType = Context.getPointerType(ExDeclType);
4999
5000 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5001 // The exception-declaration shall not denote a pointer or reference to an
5002 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005003 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005004 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005005 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005006 Invalid = true;
5007 }
Douglas Gregord308e622009-05-18 20:51:54 +00005008
Sebastian Redl4b07b292008-12-22 19:15:10 +00005009 QualType BaseType = ExDeclType;
5010 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005011 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005012 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005013 BaseType = Ptr->getPointeeType();
5014 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005015 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005016 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005017 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005018 BaseType = Ref->getPointeeType();
5019 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005020 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005021 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005022 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005023 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005024 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005025
Mike Stump1eb44332009-09-09 15:08:12 +00005026 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005027 RequireNonAbstractType(Loc, ExDeclType,
5028 diag::err_abstract_type_in_decl,
5029 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005030 Invalid = true;
5031
Douglas Gregord308e622009-05-18 20:51:54 +00005032 // FIXME: Need to test for ability to copy-construct and destroy the
5033 // exception variable.
5034
Sebastian Redl8351da02008-12-22 21:35:02 +00005035 // FIXME: Need to check for abstract classes.
5036
Mike Stump1eb44332009-09-09 15:08:12 +00005037 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005038 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005039
5040 if (Invalid)
5041 ExDecl->setInvalidDecl();
5042
5043 return ExDecl;
5044}
5045
5046/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5047/// handler.
5048Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005049 TypeSourceInfo *TInfo = 0;
5050 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005051
5052 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005053 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005054 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005055 // The scope should be freshly made just for us. There is just no way
5056 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005057 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005058 if (PrevDecl->isTemplateParameter()) {
5059 // Maybe we will complain about the shadowed template parameter.
5060 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005061 }
5062 }
5063
Chris Lattnereaaebc72009-04-25 08:06:05 +00005064 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005065 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5066 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005067 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005068 }
5069
John McCalla93c9342009-12-07 02:54:59 +00005070 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005071 D.getIdentifier(),
5072 D.getIdentifierLoc(),
5073 D.getDeclSpec().getSourceRange());
5074
Chris Lattnereaaebc72009-04-25 08:06:05 +00005075 if (Invalid)
5076 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005077
Sebastian Redl4b07b292008-12-22 19:15:10 +00005078 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005079 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005080 PushOnScopeChains(ExDecl, S);
5081 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005082 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005083
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005084 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005085 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005086}
Anders Carlssonfb311762009-03-14 00:25:26 +00005087
Mike Stump1eb44332009-09-09 15:08:12 +00005088Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005089 ExprArg assertexpr,
5090 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005091 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005092 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005093 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5094
Anders Carlssonc3082412009-03-14 00:33:21 +00005095 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5096 llvm::APSInt Value(32);
5097 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5098 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5099 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005100 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005101 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005102
Anders Carlssonc3082412009-03-14 00:33:21 +00005103 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005104 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005105 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005106 }
5107 }
Mike Stump1eb44332009-09-09 15:08:12 +00005108
Anders Carlsson77d81422009-03-15 17:35:16 +00005109 assertexpr.release();
5110 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005111 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005112 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005113
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005114 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005115 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005116}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005117
John McCalldd4a3b02009-09-16 22:47:08 +00005118/// Handle a friend type declaration. This works in tandem with
5119/// ActOnTag.
5120///
5121/// Notes on friend class templates:
5122///
5123/// We generally treat friend class declarations as if they were
5124/// declaring a class. So, for example, the elaborated type specifier
5125/// in a friend declaration is required to obey the restrictions of a
5126/// class-head (i.e. no typedefs in the scope chain), template
5127/// parameters are required to match up with simple template-ids, &c.
5128/// However, unlike when declaring a template specialization, it's
5129/// okay to refer to a template specialization without an empty
5130/// template parameter declaration, e.g.
5131/// friend class A<T>::B<unsigned>;
5132/// We permit this as a special case; if there are any template
5133/// parameters present at all, require proper matching, i.e.
5134/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005135Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005136 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005137 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005138
5139 assert(DS.isFriendSpecified());
5140 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5141
John McCalldd4a3b02009-09-16 22:47:08 +00005142 // Try to convert the decl specifier to a type. This works for
5143 // friend templates because ActOnTag never produces a ClassTemplateDecl
5144 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005145 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005146 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5147 if (TheDeclarator.isInvalidType())
5148 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005149
John McCalldd4a3b02009-09-16 22:47:08 +00005150 // This is definitely an error in C++98. It's probably meant to
5151 // be forbidden in C++0x, too, but the specification is just
5152 // poorly written.
5153 //
5154 // The problem is with declarations like the following:
5155 // template <T> friend A<T>::foo;
5156 // where deciding whether a class C is a friend or not now hinges
5157 // on whether there exists an instantiation of A that causes
5158 // 'foo' to equal C. There are restrictions on class-heads
5159 // (which we declare (by fiat) elaborated friend declarations to
5160 // be) that makes this tractable.
5161 //
5162 // FIXME: handle "template <> friend class A<T>;", which
5163 // is possibly well-formed? Who even knows?
5164 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5165 Diag(Loc, diag::err_tagless_friend_type_template)
5166 << DS.getSourceRange();
5167 return DeclPtrTy();
5168 }
5169
John McCall02cace72009-08-28 07:59:38 +00005170 // C++ [class.friend]p2:
5171 // An elaborated-type-specifier shall be used in a friend declaration
5172 // for a class.*
5173 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005174 // This is one of the rare places in Clang where it's legitimate to
5175 // ask about the "spelling" of the type.
5176 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5177 // If we evaluated the type to a record type, suggest putting
5178 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005179 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005180 RecordDecl *RD = RT->getDecl();
5181
5182 std::string InsertionText = std::string(" ") + RD->getKindName();
5183
John McCalle3af0232009-10-07 23:34:25 +00005184 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5185 << (unsigned) RD->getTagKind()
5186 << T
5187 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005188 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5189 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005190 return DeclPtrTy();
5191 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005192 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5193 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005194 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005195 }
5196 }
5197
John McCalle3af0232009-10-07 23:34:25 +00005198 // Enum types cannot be friends.
5199 if (T->getAs<EnumType>()) {
5200 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5201 << SourceRange(DS.getFriendSpecLoc());
5202 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005203 }
John McCall02cace72009-08-28 07:59:38 +00005204
John McCall02cace72009-08-28 07:59:38 +00005205 // C++98 [class.friend]p1: A friend of a class is a function
5206 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005207 // This is fixed in DR77, which just barely didn't make the C++03
5208 // deadline. It's also a very silly restriction that seriously
5209 // affects inner classes and which nobody else seems to implement;
5210 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005211
John McCalldd4a3b02009-09-16 22:47:08 +00005212 Decl *D;
5213 if (TempParams.size())
5214 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5215 TempParams.size(),
5216 (TemplateParameterList**) TempParams.release(),
5217 T.getTypePtr(),
5218 DS.getFriendSpecLoc());
5219 else
5220 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5221 DS.getFriendSpecLoc());
5222 D->setAccess(AS_public);
5223 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005224
John McCalldd4a3b02009-09-16 22:47:08 +00005225 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005226}
5227
John McCallbbbcdd92009-09-11 21:02:39 +00005228Sema::DeclPtrTy
5229Sema::ActOnFriendFunctionDecl(Scope *S,
5230 Declarator &D,
5231 bool IsDefinition,
5232 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005233 const DeclSpec &DS = D.getDeclSpec();
5234
5235 assert(DS.isFriendSpecified());
5236 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5237
5238 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005239 TypeSourceInfo *TInfo = 0;
5240 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005241
5242 // C++ [class.friend]p1
5243 // A friend of a class is a function or class....
5244 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005245 // It *doesn't* see through dependent types, which is correct
5246 // according to [temp.arg.type]p3:
5247 // If a declaration acquires a function type through a
5248 // type dependent on a template-parameter and this causes
5249 // a declaration that does not use the syntactic form of a
5250 // function declarator to have a function type, the program
5251 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005252 if (!T->isFunctionType()) {
5253 Diag(Loc, diag::err_unexpected_friend);
5254
5255 // It might be worthwhile to try to recover by creating an
5256 // appropriate declaration.
5257 return DeclPtrTy();
5258 }
5259
5260 // C++ [namespace.memdef]p3
5261 // - If a friend declaration in a non-local class first declares a
5262 // class or function, the friend class or function is a member
5263 // of the innermost enclosing namespace.
5264 // - The name of the friend is not found by simple name lookup
5265 // until a matching declaration is provided in that namespace
5266 // scope (either before or after the class declaration granting
5267 // friendship).
5268 // - If a friend function is called, its name may be found by the
5269 // name lookup that considers functions from namespaces and
5270 // classes associated with the types of the function arguments.
5271 // - When looking for a prior declaration of a class or a function
5272 // declared as a friend, scopes outside the innermost enclosing
5273 // namespace scope are not considered.
5274
John McCall02cace72009-08-28 07:59:38 +00005275 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5276 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005277 assert(Name);
5278
John McCall67d1a672009-08-06 02:15:43 +00005279 // The context we found the declaration in, or in which we should
5280 // create the declaration.
5281 DeclContext *DC;
5282
5283 // FIXME: handle local classes
5284
5285 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005286 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5287 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005288 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005289 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005290 DC = computeDeclContext(ScopeQual);
5291
5292 // FIXME: handle dependent contexts
5293 if (!DC) return DeclPtrTy();
5294
John McCall68263142009-11-18 22:49:29 +00005295 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005296
5297 // If searching in that context implicitly found a declaration in
5298 // a different context, treat it like it wasn't found at all.
5299 // TODO: better diagnostics for this case. Suggesting the right
5300 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005301 // FIXME: getRepresentativeDecl() is not right here at all
5302 if (Previous.empty() ||
5303 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005304 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005305 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5306 return DeclPtrTy();
5307 }
5308
5309 // C++ [class.friend]p1: A friend of a class is a function or
5310 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005311 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005312 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5313
John McCall67d1a672009-08-06 02:15:43 +00005314 // Otherwise walk out to the nearest namespace scope looking for matches.
5315 } else {
5316 // TODO: handle local class contexts.
5317
5318 DC = CurContext;
5319 while (true) {
5320 // Skip class contexts. If someone can cite chapter and verse
5321 // for this behavior, that would be nice --- it's what GCC and
5322 // EDG do, and it seems like a reasonable intent, but the spec
5323 // really only says that checks for unqualified existing
5324 // declarations should stop at the nearest enclosing namespace,
5325 // not that they should only consider the nearest enclosing
5326 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005327 while (DC->isRecord())
5328 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005329
John McCall68263142009-11-18 22:49:29 +00005330 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005331
5332 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005333 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005334 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005335
John McCall67d1a672009-08-06 02:15:43 +00005336 if (DC->isFileContext()) break;
5337 DC = DC->getParent();
5338 }
5339
5340 // C++ [class.friend]p1: A friend of a class is a function or
5341 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005342 // C++0x changes this for both friend types and functions.
5343 // Most C++ 98 compilers do seem to give an error here, so
5344 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005345 if (!Previous.empty() && DC->Equals(CurContext)
5346 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005347 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5348 }
5349
Douglas Gregor182ddf02009-09-28 00:08:27 +00005350 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005351 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005352 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5353 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5354 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005355 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005356 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5357 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005358 return DeclPtrTy();
5359 }
John McCall67d1a672009-08-06 02:15:43 +00005360 }
5361
Douglas Gregor182ddf02009-09-28 00:08:27 +00005362 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005363 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005364 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005365 IsDefinition,
5366 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005367 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005368
Douglas Gregor182ddf02009-09-28 00:08:27 +00005369 assert(ND->getDeclContext() == DC);
5370 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005371
John McCallab88d972009-08-31 22:39:49 +00005372 // Add the function declaration to the appropriate lookup tables,
5373 // adjusting the redeclarations list as necessary. We don't
5374 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005375 //
John McCallab88d972009-08-31 22:39:49 +00005376 // Also update the scope-based lookup if the target context's
5377 // lookup context is in lexical scope.
5378 if (!CurContext->isDependentContext()) {
5379 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005380 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005381 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005382 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005383 }
John McCall02cace72009-08-28 07:59:38 +00005384
5385 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005386 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005387 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005388 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005389 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005390
Douglas Gregor7557a132009-12-24 20:56:24 +00005391 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5392 FrD->setSpecialization(true);
5393
Douglas Gregor182ddf02009-09-28 00:08:27 +00005394 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005395}
5396
Chris Lattnerb28317a2009-03-28 19:18:32 +00005397void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005398 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Chris Lattnerb28317a2009-03-28 19:18:32 +00005400 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005401 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5402 if (!Fn) {
5403 Diag(DelLoc, diag::err_deleted_non_function);
5404 return;
5405 }
5406 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5407 Diag(DelLoc, diag::err_deleted_decl_not_first);
5408 Diag(Prev->getLocation(), diag::note_previous_declaration);
5409 // If the declaration wasn't the first, we delete the function anyway for
5410 // recovery.
5411 }
5412 Fn->setDeleted();
5413}
Sebastian Redl13e88542009-04-27 21:33:24 +00005414
5415static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5416 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5417 ++CI) {
5418 Stmt *SubStmt = *CI;
5419 if (!SubStmt)
5420 continue;
5421 if (isa<ReturnStmt>(SubStmt))
5422 Self.Diag(SubStmt->getSourceRange().getBegin(),
5423 diag::err_return_in_constructor_handler);
5424 if (!isa<Expr>(SubStmt))
5425 SearchForReturnInStmt(Self, SubStmt);
5426 }
5427}
5428
5429void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5430 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5431 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5432 SearchForReturnInStmt(*this, Handler);
5433 }
5434}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005435
Mike Stump1eb44332009-09-09 15:08:12 +00005436bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005437 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005438 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5439 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005440
5441 QualType CNewTy = Context.getCanonicalType(NewTy);
5442 QualType COldTy = Context.getCanonicalType(OldTy);
5443
Mike Stump1eb44332009-09-09 15:08:12 +00005444 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00005445 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005446 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005447
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005448 // Check if the return types are covariant
5449 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005450
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005451 /// Both types must be pointers or references to classes.
5452 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5453 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5454 NewClassTy = NewPT->getPointeeType();
5455 OldClassTy = OldPT->getPointeeType();
5456 }
5457 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5458 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5459 NewClassTy = NewRT->getPointeeType();
5460 OldClassTy = OldRT->getPointeeType();
5461 }
5462 }
Mike Stump1eb44332009-09-09 15:08:12 +00005463
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005464 // The return types aren't either both pointers or references to a class type.
5465 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005466 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005467 diag::err_different_return_type_for_overriding_virtual_function)
5468 << New->getDeclName() << NewTy << OldTy;
5469 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005470
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005471 return true;
5472 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005473
Douglas Gregora4923eb2009-11-16 21:35:15 +00005474 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005475 // Check if the new class derives from the old class.
5476 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5477 Diag(New->getLocation(),
5478 diag::err_covariant_return_not_derived)
5479 << New->getDeclName() << NewTy << OldTy;
5480 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5481 return true;
5482 }
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005484 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005485 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005486 diag::err_covariant_return_inaccessible_base,
5487 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5488 // FIXME: Should this point to the return type?
5489 New->getLocation(), SourceRange(), New->getDeclName())) {
5490 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5491 return true;
5492 }
5493 }
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005495 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005496 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005497 Diag(New->getLocation(),
5498 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005499 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005500 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5501 return true;
5502 };
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005504
5505 // The new class type must have the same or less qualifiers as the old type.
5506 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5507 Diag(New->getLocation(),
5508 diag::err_covariant_return_type_class_type_more_qualified)
5509 << New->getDeclName() << NewTy << OldTy;
5510 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5511 return true;
5512 };
Mike Stump1eb44332009-09-09 15:08:12 +00005513
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005514 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005515}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005516
Sean Huntbbd37c62009-11-21 08:43:09 +00005517bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5518 const CXXMethodDecl *Old)
5519{
5520 if (Old->hasAttr<FinalAttr>()) {
5521 Diag(New->getLocation(), diag::err_final_function_overridden)
5522 << New->getDeclName();
5523 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5524 return true;
5525 }
5526
5527 return false;
5528}
5529
Douglas Gregor4ba31362009-12-01 17:24:26 +00005530/// \brief Mark the given method pure.
5531///
5532/// \param Method the method to be marked pure.
5533///
5534/// \param InitRange the source range that covers the "0" initializer.
5535bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5536 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5537 Method->setPure();
5538
5539 // A class is abstract if at least one function is pure virtual.
5540 Method->getParent()->setAbstract(true);
5541 return false;
5542 }
5543
5544 if (!Method->isInvalidDecl())
5545 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5546 << Method->getDeclName() << InitRange;
5547 return true;
5548}
5549
John McCall731ad842009-12-19 09:28:58 +00005550/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5551/// an initializer for the out-of-line declaration 'Dcl'. The scope
5552/// is a fresh scope pushed for just this purpose.
5553///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005554/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5555/// static data member of class X, names should be looked up in the scope of
5556/// class X.
5557void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005558 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005559 Decl *D = Dcl.getAs<Decl>();
5560 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005561
John McCall731ad842009-12-19 09:28:58 +00005562 // We should only get called for declarations with scope specifiers, like:
5563 // int foo::bar;
5564 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005565 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005566}
5567
5568/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005569/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005570void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005571 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005572 Decl *D = Dcl.getAs<Decl>();
5573 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005574
John McCall731ad842009-12-19 09:28:58 +00005575 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005576 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005577}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005578
5579/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5580/// C++ if/switch/while/for statement.
5581/// e.g: "if (int x = f()) {...}"
5582Action::DeclResult
5583Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5584 // C++ 6.4p2:
5585 // The declarator shall not specify a function or an array.
5586 // The type-specifier-seq shall not contain typedef and shall not declare a
5587 // new class or enumeration.
5588 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5589 "Parser allowed 'typedef' as storage class of condition decl.");
5590
John McCalla93c9342009-12-07 02:54:59 +00005591 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005592 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005593 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005594
5595 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5596 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5597 // would be created and CXXConditionDeclExpr wants a VarDecl.
5598 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5599 << D.getSourceRange();
5600 return DeclResult();
5601 } else if (OwnedTag && OwnedTag->isDefinition()) {
5602 // The type-specifier-seq shall not declare a new class or enumeration.
5603 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5604 }
5605
5606 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5607 if (!Dcl)
5608 return DeclResult();
5609
5610 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5611 VD->setDeclaredInCondition(true);
5612 return Dcl;
5613}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005614
Anders Carlssond6a637f2009-12-07 08:24:59 +00005615void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5616 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005617 // Ignore dependent types.
5618 if (MD->isDependentContext())
5619 return;
5620
5621 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005622
5623 // Ignore classes without a vtable.
5624 if (!RD->isDynamicClass())
5625 return;
5626
Anders Carlssond6a637f2009-12-07 08:24:59 +00005627 if (!MD->isOutOfLine()) {
5628 // The only inline functions we care about are constructors. We also defer
5629 // marking the virtual members as referenced until we've reached the end
5630 // of the translation unit. We do this because we need to know the key
5631 // function of the class in order to determine the key function.
5632 if (isa<CXXConstructorDecl>(MD))
5633 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5634 return;
5635 }
5636
Anders Carlssonf53df232009-12-07 04:35:11 +00005637 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005638
5639 if (!KeyFunction) {
5640 // This record does not have a key function, so we assume that the vtable
5641 // will be emitted when it's used by the constructor.
5642 if (!isa<CXXConstructorDecl>(MD))
5643 return;
5644 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5645 // We don't have the right key function.
5646 return;
5647 }
5648
Anders Carlssond6a637f2009-12-07 08:24:59 +00005649 // Mark the members as referenced.
5650 MarkVirtualMembersReferenced(Loc, RD);
5651 ClassesWithUnmarkedVirtualMembers.erase(RD);
5652}
5653
5654bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5655 if (ClassesWithUnmarkedVirtualMembers.empty())
5656 return false;
5657
5658 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5659 ClassesWithUnmarkedVirtualMembers.begin(),
5660 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5661 CXXRecordDecl *RD = i->first;
5662
5663 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5664 if (KeyFunction) {
5665 // We know that the class has a key function. If the key function was
5666 // declared in this translation unit, then it the class decl would not
5667 // have been in the ClassesWithUnmarkedVirtualMembers map.
5668 continue;
5669 }
5670
5671 SourceLocation Loc = i->second;
5672 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005673 }
5674
Anders Carlssond6a637f2009-12-07 08:24:59 +00005675 ClassesWithUnmarkedVirtualMembers.clear();
5676 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005677}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005678
5679void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5680 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5681 e = RD->method_end(); i != e; ++i) {
5682 CXXMethodDecl *MD = *i;
5683
5684 // C++ [basic.def.odr]p2:
5685 // [...] A virtual member function is used if it is not pure. [...]
5686 if (MD->isVirtual() && !MD->isPure())
5687 MarkDeclarationReferenced(Loc, MD);
5688 }
5689}
5690