blob: c73c6caf2973cdd4b80550a3b97e8d5a204d1650 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
John McCallbf73b352010-03-12 18:31:32 +0000301 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000302 if (OldParam->hasUninstantiatedDefaultArg())
303 NewParam->setUninstantiatedDefaultArg(
304 OldParam->getUninstantiatedDefaultArg());
305 else
306 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000307 } else if (NewParam->hasDefaultArg()) {
308 if (New->getDescribedFunctionTemplate()) {
309 // Paragraph 4, quoted above, only applies to non-template functions.
310 Diag(NewParam->getLocation(),
311 diag::err_param_default_argument_template_redecl)
312 << NewParam->getDefaultArgRange();
313 Diag(Old->getLocation(), diag::note_template_prev_declaration)
314 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000315 } else if (New->getTemplateSpecializationKind()
316 != TSK_ImplicitInstantiation &&
317 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318 // C++ [temp.expr.spec]p21:
319 // Default function arguments shall not be specified in a declaration
320 // or a definition for one of the following explicit specializations:
321 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000322 // - the explicit specialization of a member function template;
323 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000324 // template where the class template specialization to which the
325 // member function specialization belongs is implicitly
326 // instantiated.
327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329 << New->getDeclName()
330 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000331 } else if (New->getDeclContext()->isDependentContext()) {
332 // C++ [dcl.fct.default]p6 (DR217):
333 // Default arguments for a member function of a class template shall
334 // be specified on the initial declaration of the member function
335 // within the class template.
336 //
337 // Reading the tea leaves a bit in DR217 and its reference to DR205
338 // leads me to the conclusion that one cannot add default function
339 // arguments for an out-of-line definition of a member function of a
340 // dependent type.
341 int WhichKind = 2;
342 if (CXXRecordDecl *Record
343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344 if (Record->getDescribedClassTemplate())
345 WhichKind = 0;
346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347 WhichKind = 1;
348 else
349 WhichKind = 2;
350 }
351
352 Diag(NewParam->getLocation(),
353 diag::err_param_default_argument_member_template_redecl)
354 << WhichKind
355 << NewParam->getDefaultArgRange();
356 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000357 }
358 }
359
Douglas Gregore13ad832010-02-12 07:32:17 +0000360 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362
Douglas Gregorcda9c672009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 else
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000412 if (!Param->hasUnparsedDefaultArg())
413 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 Param->setDefaultArg(0);
415 }
416 }
417 }
418}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000419
Douglas Gregorb48fe382008-10-31 09:07:45 +0000420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000426 assert(getLangOptions().CPlusPlus && "No class names in C!");
427
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000428 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000429 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000430 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
432 } else
433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
434
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000435 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000436 return &II == CurDecl->getIdentifier();
437 else
438 return false;
439}
440
Mike Stump1eb44332009-09-09 15:08:12 +0000441/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000442///
443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
444/// and returns NULL otherwise.
445CXXBaseSpecifier *
446Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
447 SourceRange SpecifierRange,
448 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000450 SourceLocation BaseLoc) {
451 // C++ [class.union]p1:
452 // A union shall not have base classes.
453 if (Class->isUnion()) {
454 Diag(Class->getLocation(), diag::err_base_clause_on_union)
455 << SpecifierRange;
456 return 0;
457 }
458
459 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000461 Class->getTagKind() == RecordDecl::TK_class,
462 Access, BaseType);
463
464 // Base specifiers must be record types.
465 if (!BaseType->isRecordType()) {
466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
467 return 0;
468 }
469
470 // C++ [class.union]p1:
471 // A union shall not be used as a base class.
472 if (BaseType->isUnionType()) {
473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
474 return 0;
475 }
476
477 // C++ [class.derived]p2:
478 // The class-name in a base-specifier shall not be an incompletely
479 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000480 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000481 PDiag(diag::err_incomplete_base_class)
482 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000483 return 0;
484
Eli Friedman1d954f62009-08-15 21:55:26 +0000485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000487 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000488 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000489 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000490 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
491 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000492
Sean Huntbbd37c62009-11-21 08:43:09 +0000493 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
494 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
495 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000496 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
497 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000498 return 0;
499 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000500
Eli Friedmand0137332009-12-05 23:03:49 +0000501 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000502
503 // Create the base specifier.
504 // FIXME: Allocate via ASTContext?
505 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
506 Class->getTagKind() == RecordDecl::TK_class,
507 Access, BaseType);
508}
509
510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
511 const CXXRecordDecl *BaseClass,
512 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000513 // A class with a non-empty base class is not empty.
514 // FIXME: Standard ref?
515 if (!BaseClass->isEmpty())
516 Class->setEmpty(false);
517
518 // C++ [class.virtual]p1:
519 // A class that [...] inherits a virtual function is called a polymorphic
520 // class.
521 if (BaseClass->isPolymorphic())
522 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000523
Douglas Gregor2943aed2009-03-03 04:44:36 +0000524 // C++ [dcl.init.aggr]p1:
525 // An aggregate is [...] a class with [...] no base classes [...].
526 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000527
528 // C++ [class]p4:
529 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000530 Class->setPOD(false);
531
Anders Carlsson51f94042009-12-03 17:49:57 +0000532 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000533 // C++ [class.ctor]p5:
534 // A constructor is trivial if its class has no virtual base classes.
535 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000536
537 // C++ [class.copy]p6:
538 // A copy constructor is trivial if its class has no virtual base classes.
539 Class->setHasTrivialCopyConstructor(false);
540
541 // C++ [class.copy]p11:
542 // A copy assignment operator is trivial if its class has no virtual
543 // base classes.
544 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000545
546 // C++0x [meta.unary.prop] is_empty:
547 // T is a class type, but not a union type, with ... no virtual base
548 // classes
549 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000550 } else {
551 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000552 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000553 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000554 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000555 Class->setHasTrivialConstructor(false);
556
557 // C++ [class.copy]p6:
558 // A copy constructor is trivial if all the direct base classes of its
559 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000560 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000561 Class->setHasTrivialCopyConstructor(false);
562
563 // C++ [class.copy]p11:
564 // A copy assignment operator is trivial if all the direct base classes
565 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000566 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000567 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000568 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000569
570 // C++ [class.ctor]p3:
571 // A destructor is trivial if all the direct base classes of its class
572 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000573 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000574 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575}
576
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
578/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000579/// example:
580/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000581/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000582Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000584 bool Virtual, AccessSpecifier Access,
585 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000586 if (!classdecl)
587 return true;
588
Douglas Gregor40808ce2009-03-09 23:48:35 +0000589 AdjustDeclIfTemplate(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000590 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
591 if (!Class)
592 return true;
593
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000594 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
596 Virtual, Access,
597 BaseType, BaseLoc))
598 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Douglas Gregor2943aed2009-03-03 04:44:36 +0000600 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000601}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000602
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603/// \brief Performs the actual work of attaching the given base class
604/// specifiers to a C++ class.
605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
606 unsigned NumBases) {
607 if (NumBases == 0)
608 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609
610 // Used to keep track of which base types we have already seen, so
611 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000612 // that the key is always the unqualified canonical type of the base
613 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000614 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
615
616 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000620 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000622 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000623
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000624 if (KnownBaseTypes[NewBaseType]) {
625 // C++ [class.mi]p3:
626 // A class shall not be specified as a direct base class of a
627 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000628 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000629 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000630 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000632
633 // Delete the duplicate base class specifier; we're going to
634 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000635 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636
637 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 } else {
639 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000640 KnownBaseTypes[NewBaseType] = Bases[idx];
641 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000642 }
643 }
644
645 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000646 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000647
648 // Delete the remaining (good) base class specifiers, since their
649 // data has been copied into the CXXRecordDecl.
650 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000651 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000652
653 return Invalid;
654}
655
656/// ActOnBaseSpecifiers - Attach the given base specifiers to the
657/// class, after checking whether there are any duplicate base
658/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000659void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000660 unsigned NumBases) {
661 if (!ClassDecl || !Bases || !NumBases)
662 return;
663
664 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000666 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000667}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000668
John McCall3cb0ebd2010-03-10 03:28:59 +0000669static CXXRecordDecl *GetClassForType(QualType T) {
670 if (const RecordType *RT = T->getAs<RecordType>())
671 return cast<CXXRecordDecl>(RT->getDecl());
672 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
673 return ICT->getDecl();
674 else
675 return 0;
676}
677
Douglas Gregora8f32e02009-10-06 17:59:45 +0000678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000683
684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 return false;
687
John McCall3cb0ebd2010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000690 return false;
691
John McCall86ff3082010-02-04 22:26:26 +0000692 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
693 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000694}
695
696/// \brief Determine whether the type \p Derived is a C++ class that is
697/// derived from the type \p Base.
698bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
699 if (!getLangOptions().CPlusPlus)
700 return false;
701
John McCall3cb0ebd2010-03-10 03:28:59 +0000702 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
703 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000704 return false;
705
John McCall3cb0ebd2010-03-10 03:28:59 +0000706 CXXRecordDecl *BaseRD = GetClassForType(Base);
707 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000708 return false;
709
Douglas Gregora8f32e02009-10-06 17:59:45 +0000710 return DerivedRD->isDerivedFrom(BaseRD, Paths);
711}
712
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000713void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
714 CXXBaseSpecifierArray &BasePathArray) {
715 assert(BasePathArray.empty() && "Base path array must be empty!");
716 assert(Paths.isRecordingPaths() && "Must record paths!");
717
718 const CXXBasePath &Path = Paths.front();
719
720 // We first go backward and check if we have a virtual base.
721 // FIXME: It would be better if CXXBasePath had the base specifier for
722 // the nearest virtual base.
723 unsigned Start = 0;
724 for (unsigned I = Path.size(); I != 0; --I) {
725 if (Path[I - 1].Base->isVirtual()) {
726 Start = I - 1;
727 break;
728 }
729 }
730
731 // Now add all bases.
732 for (unsigned I = Start, E = Path.size(); I != E; ++I)
733 BasePathArray.push_back(Path[I].Base);
734}
735
Douglas Gregora8f32e02009-10-06 17:59:45 +0000736/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
737/// conversion (where Derived and Base are class types) is
738/// well-formed, meaning that the conversion is unambiguous (and
739/// that all of the base classes are accessible). Returns true
740/// and emits a diagnostic if the code is ill-formed, returns false
741/// otherwise. Loc is the location where this routine should point to
742/// if there is an error, and Range is the source range to highlight
743/// if there is an error.
744bool
745Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000746 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 unsigned AmbigiousBaseConvID,
748 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000749 DeclarationName Name,
750 CXXBaseSpecifierArray *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000751 // First, determine whether the path from Derived to Base is
752 // ambiguous. This is slightly more expensive than checking whether
753 // the Derived to Base conversion exists, because here we need to
754 // explore multiple paths to determine if there is an ambiguity.
755 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
756 /*DetectVirtual=*/false);
757 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
758 assert(DerivationOkay &&
759 "Can only be used with a derived-to-base conversion");
760 (void)DerivationOkay;
761
762 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000763 if (InaccessibleBaseID) {
764 // Check that the base class can be accessed.
765 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
766 InaccessibleBaseID)) {
767 case AR_inaccessible:
768 return true;
769 case AR_accessible:
770 case AR_dependent:
771 case AR_delayed:
772 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000773 }
John McCall6b2accb2010-02-10 09:31:12 +0000774 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000775
776 // Build a base path if necessary.
777 if (BasePath)
778 BuildBasePathArray(Paths, *BasePath);
779 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000780 }
781
782 // We know that the derived-to-base conversion is ambiguous, and
783 // we're going to produce a diagnostic. Perform the derived-to-base
784 // search just one more time to compute all of the possible paths so
785 // that we can print them out. This is more expensive than any of
786 // the previous derived-to-base checks we've done, but at this point
787 // performance isn't as much of an issue.
788 Paths.clear();
789 Paths.setRecordingPaths(true);
790 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
791 assert(StillOkay && "Can only be used with a derived-to-base conversion");
792 (void)StillOkay;
793
794 // Build up a textual representation of the ambiguous paths, e.g.,
795 // D -> B -> A, that will be used to illustrate the ambiguous
796 // conversions in the diagnostic. We only print one of the paths
797 // to each base class subobject.
798 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
799
800 Diag(Loc, AmbigiousBaseConvID)
801 << Derived << Base << PathDisplayStr << Range << Name;
802 return true;
803}
804
805bool
806Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000807 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000808 CXXBaseSpecifierArray *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000809 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000810 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000811 IgnoreAccess ? 0
812 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000813 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000814 Loc, Range, DeclarationName(),
815 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000816}
817
818
819/// @brief Builds a string representing ambiguous paths from a
820/// specific derived class to different subobjects of the same base
821/// class.
822///
823/// This function builds a string that can be used in error messages
824/// to show the different paths that one can take through the
825/// inheritance hierarchy to go from the derived class to different
826/// subobjects of a base class. The result looks something like this:
827/// @code
828/// struct D -> struct B -> struct A
829/// struct D -> struct C -> struct A
830/// @endcode
831std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
832 std::string PathDisplayStr;
833 std::set<unsigned> DisplayedPaths;
834 for (CXXBasePaths::paths_iterator Path = Paths.begin();
835 Path != Paths.end(); ++Path) {
836 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
837 // We haven't displayed a path to this particular base
838 // class subobject yet.
839 PathDisplayStr += "\n ";
840 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
841 for (CXXBasePath::const_iterator Element = Path->begin();
842 Element != Path->end(); ++Element)
843 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
844 }
845 }
846
847 return PathDisplayStr;
848}
849
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000850//===----------------------------------------------------------------------===//
851// C++ class member Handling
852//===----------------------------------------------------------------------===//
853
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000854/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
855/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
856/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000857/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000858Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000859Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000860 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000861 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
862 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000863 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000864 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000865 Expr *BitWidth = static_cast<Expr*>(BW);
866 Expr *Init = static_cast<Expr*>(InitExpr);
867 SourceLocation Loc = D.getIdentifierLoc();
868
Sebastian Redl669d5d72008-11-14 23:42:31 +0000869 bool isFunc = D.isFunctionDeclarator();
870
John McCall67d1a672009-08-06 02:15:43 +0000871 assert(!DS.isFriendSpecified());
872
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873 // C++ 9.2p6: A member shall not be declared to have automatic storage
874 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000875 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
876 // data members and cannot be applied to names declared const or static,
877 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000878 switch (DS.getStorageClassSpec()) {
879 case DeclSpec::SCS_unspecified:
880 case DeclSpec::SCS_typedef:
881 case DeclSpec::SCS_static:
882 // FALL THROUGH.
883 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000884 case DeclSpec::SCS_mutable:
885 if (isFunc) {
886 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000887 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000888 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000889 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Sebastian Redla11f42f2008-11-17 23:24:37 +0000891 // FIXME: It would be nicer if the keyword was ignored only for this
892 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000893 D.getMutableDeclSpec().ClearStorageClassSpecs();
894 } else {
895 QualType T = GetTypeForDeclarator(D, S);
896 diag::kind err = static_cast<diag::kind>(0);
897 if (T->isReferenceType())
898 err = diag::err_mutable_reference;
899 else if (T.isConstQualified())
900 err = diag::err_mutable_const;
901 if (err != 0) {
902 if (DS.getStorageClassSpecLoc().isValid())
903 Diag(DS.getStorageClassSpecLoc(), err);
904 else
905 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000906 // FIXME: It would be nicer if the keyword was ignored only for this
907 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000908 D.getMutableDeclSpec().ClearStorageClassSpecs();
909 }
910 }
911 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000912 default:
913 if (DS.getStorageClassSpecLoc().isValid())
914 Diag(DS.getStorageClassSpecLoc(),
915 diag::err_storageclass_invalid_for_member);
916 else
917 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
918 D.getMutableDeclSpec().ClearStorageClassSpecs();
919 }
920
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000921 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000922 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000923 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000924 // Check also for this case:
925 //
926 // typedef int f();
927 // f a;
928 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000929 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000930 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000931 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000932
Sebastian Redl669d5d72008-11-14 23:42:31 +0000933 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
934 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000935 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000936
937 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000938 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000939 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000940 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
941 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000942 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000943 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000944 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000945 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000946 if (!Member) {
947 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000948 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000949 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000950
951 // Non-instance-fields can't have a bitfield.
952 if (BitWidth) {
953 if (Member->isInvalidDecl()) {
954 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000955 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000956 // C++ 9.6p3: A bit-field shall not be a static member.
957 // "static member 'A' cannot be a bit-field"
958 Diag(Loc, diag::err_static_not_bitfield)
959 << Name << BitWidth->getSourceRange();
960 } else if (isa<TypedefDecl>(Member)) {
961 // "typedef member 'x' cannot be a bit-field"
962 Diag(Loc, diag::err_typedef_not_bitfield)
963 << Name << BitWidth->getSourceRange();
964 } else {
965 // A function typedef ("typedef int f(); f a;").
966 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
967 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000968 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000969 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattner8b963ef2009-03-05 23:01:03 +0000972 DeleteExpr(BitWidth);
973 BitWidth = 0;
974 Member->setInvalidDecl();
975 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000976
977 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregor37b372b2009-08-20 22:52:58 +0000979 // If we have declared a member function template, set the access of the
980 // templated declaration as well.
981 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
982 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000983 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000984
Douglas Gregor10bd3682008-11-17 22:58:34 +0000985 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000986
Douglas Gregor021c3b32009-03-11 23:00:04 +0000987 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000988 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000989 if (Deleted) // FIXME: Source location is not very good.
990 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000991
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000993 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000994 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000995 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000996 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000997}
998
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000999/// \brief Find the direct and/or virtual base specifiers that
1000/// correspond to the given base type, for use in base initialization
1001/// within a constructor.
1002static bool FindBaseInitializer(Sema &SemaRef,
1003 CXXRecordDecl *ClassDecl,
1004 QualType BaseType,
1005 const CXXBaseSpecifier *&DirectBaseSpec,
1006 const CXXBaseSpecifier *&VirtualBaseSpec) {
1007 // First, check for a direct base class.
1008 DirectBaseSpec = 0;
1009 for (CXXRecordDecl::base_class_const_iterator Base
1010 = ClassDecl->bases_begin();
1011 Base != ClassDecl->bases_end(); ++Base) {
1012 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1013 // We found a direct base of this type. That's what we're
1014 // initializing.
1015 DirectBaseSpec = &*Base;
1016 break;
1017 }
1018 }
1019
1020 // Check for a virtual base class.
1021 // FIXME: We might be able to short-circuit this if we know in advance that
1022 // there are no virtual bases.
1023 VirtualBaseSpec = 0;
1024 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1025 // We haven't found a base yet; search the class hierarchy for a
1026 // virtual base class.
1027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1028 /*DetectVirtual=*/false);
1029 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1030 BaseType, Paths)) {
1031 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1032 Path != Paths.end(); ++Path) {
1033 if (Path->back().Base->isVirtual()) {
1034 VirtualBaseSpec = Path->back().Base;
1035 break;
1036 }
1037 }
1038 }
1039 }
1040
1041 return DirectBaseSpec || VirtualBaseSpec;
1042}
1043
Douglas Gregor7ad83902008-11-05 04:29:56 +00001044/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001045Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001046Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001047 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001048 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001049 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001050 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001051 SourceLocation IdLoc,
1052 SourceLocation LParenLoc,
1053 ExprTy **Args, unsigned NumArgs,
1054 SourceLocation *CommaLocs,
1055 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001056 if (!ConstructorD)
1057 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001059 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
1061 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001062 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001063 if (!Constructor) {
1064 // The user wrote a constructor initializer on a function that is
1065 // not a C++ constructor. Ignore the error for now, because we may
1066 // have more member initializers coming; we'll diagnose it just
1067 // once in ActOnMemInitializers.
1068 return true;
1069 }
1070
1071 CXXRecordDecl *ClassDecl = Constructor->getParent();
1072
1073 // C++ [class.base.init]p2:
1074 // Names in a mem-initializer-id are looked up in the scope of the
1075 // constructor’s class and, if not found in that scope, are looked
1076 // up in the scope containing the constructor’s
1077 // definition. [Note: if the constructor’s class contains a member
1078 // with the same name as a direct or virtual base class of the
1079 // class, a mem-initializer-id naming the member or base class and
1080 // composed of a single identifier refers to the class member. A
1081 // mem-initializer-id for the hidden base class may be specified
1082 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001083 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001084 // Look for a member, first.
1085 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001086 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001087 = ClassDecl->lookup(MemberOrBase);
1088 if (Result.first != Result.second)
1089 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001090
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001091 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001092
Eli Friedman59c04372009-07-29 19:44:27 +00001093 if (Member)
1094 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001095 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001096 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001097 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001098 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001099 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001100
1101 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001102 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001103 } else {
1104 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1105 LookupParsedName(R, S, &SS);
1106
1107 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1108 if (!TyD) {
1109 if (R.isAmbiguous()) return true;
1110
John McCallfd225442010-04-09 19:01:14 +00001111 // We don't want access-control diagnostics here.
1112 R.suppressDiagnostics();
1113
Douglas Gregor7a886e12010-01-19 06:46:48 +00001114 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1115 bool NotUnknownSpecialization = false;
1116 DeclContext *DC = computeDeclContext(SS, false);
1117 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1118 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1119
1120 if (!NotUnknownSpecialization) {
1121 // When the scope specifier can refer to a member of an unknown
1122 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001123 BaseType = CheckTypenameType(ETK_None,
1124 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregor7a886e12010-01-19 06:46:48 +00001125 *MemberOrBase, SS.getRange());
Douglas Gregora50ce322010-03-07 23:26:22 +00001126 if (BaseType.isNull())
1127 return true;
1128
Douglas Gregor7a886e12010-01-19 06:46:48 +00001129 R.clear();
1130 }
1131 }
1132
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001133 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001134 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001135 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1136 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001137 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1138 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1139 // We have found a non-static data member with a similar
1140 // name to what was typed; complain and initialize that
1141 // member.
1142 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1143 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001144 << FixItHint::CreateReplacement(R.getNameLoc(),
1145 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001146 Diag(Member->getLocation(), diag::note_previous_decl)
1147 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001148
1149 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1150 LParenLoc, RParenLoc);
1151 }
1152 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1153 const CXXBaseSpecifier *DirectBaseSpec;
1154 const CXXBaseSpecifier *VirtualBaseSpec;
1155 if (FindBaseInitializer(*this, ClassDecl,
1156 Context.getTypeDeclType(Type),
1157 DirectBaseSpec, VirtualBaseSpec)) {
1158 // We have found a direct or virtual base class with a
1159 // similar name to what was typed; complain and initialize
1160 // that base class.
1161 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1162 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001163 << FixItHint::CreateReplacement(R.getNameLoc(),
1164 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001165
1166 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1167 : VirtualBaseSpec;
1168 Diag(BaseSpec->getSourceRange().getBegin(),
1169 diag::note_base_class_specified_here)
1170 << BaseSpec->getType()
1171 << BaseSpec->getSourceRange();
1172
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001173 TyD = Type;
1174 }
1175 }
1176 }
1177
Douglas Gregor7a886e12010-01-19 06:46:48 +00001178 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001179 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1180 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1181 return true;
1182 }
John McCall2b194412009-12-21 10:41:20 +00001183 }
1184
Douglas Gregor7a886e12010-01-19 06:46:48 +00001185 if (BaseType.isNull()) {
1186 BaseType = Context.getTypeDeclType(TyD);
1187 if (SS.isSet()) {
1188 NestedNameSpecifier *Qualifier =
1189 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001190
Douglas Gregor7a886e12010-01-19 06:46:48 +00001191 // FIXME: preserve source range information
1192 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1193 }
John McCall2b194412009-12-21 10:41:20 +00001194 }
1195 }
Mike Stump1eb44332009-09-09 15:08:12 +00001196
John McCalla93c9342009-12-07 02:54:59 +00001197 if (!TInfo)
1198 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001199
John McCalla93c9342009-12-07 02:54:59 +00001200 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001201 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001202}
1203
John McCallb4190042009-11-04 23:02:40 +00001204/// Checks an initializer expression for use of uninitialized fields, such as
1205/// containing the field that is being initialized. Returns true if there is an
1206/// uninitialized field was used an updates the SourceLocation parameter; false
1207/// otherwise.
1208static bool InitExprContainsUninitializedFields(const Stmt* S,
1209 const FieldDecl* LhsField,
1210 SourceLocation* L) {
1211 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1212 if (ME) {
1213 const NamedDecl* RhsField = ME->getMemberDecl();
1214 if (RhsField == LhsField) {
1215 // Initializing a field with itself. Throw a warning.
1216 // But wait; there are exceptions!
1217 // Exception #1: The field may not belong to this record.
1218 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1219 const Expr* base = ME->getBase();
1220 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1221 // Even though the field matches, it does not belong to this record.
1222 return false;
1223 }
1224 // None of the exceptions triggered; return true to indicate an
1225 // uninitialized field was used.
1226 *L = ME->getMemberLoc();
1227 return true;
1228 }
1229 }
1230 bool found = false;
1231 for (Stmt::const_child_iterator it = S->child_begin();
1232 it != S->child_end() && found == false;
1233 ++it) {
1234 if (isa<CallExpr>(S)) {
1235 // Do not descend into function calls or constructors, as the use
1236 // of an uninitialized field may be valid. One would have to inspect
1237 // the contents of the function/ctor to determine if it is safe or not.
1238 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1239 // may be safe, depending on what the function/ctor does.
1240 continue;
1241 }
1242 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1243 }
1244 return found;
1245}
1246
Eli Friedman59c04372009-07-29 19:44:27 +00001247Sema::MemInitResult
1248Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1249 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001250 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001251 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001252 // Diagnose value-uses of fields to initialize themselves, e.g.
1253 // foo(foo)
1254 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001255 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001256 for (unsigned i = 0; i < NumArgs; ++i) {
1257 SourceLocation L;
1258 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1259 // FIXME: Return true in the case when other fields are used before being
1260 // uninitialized. For example, let this field be the i'th field. When
1261 // initializing the i'th field, throw a warning if any of the >= i'th
1262 // fields are used, as they are not yet initialized.
1263 // Right now we are only handling the case where the i'th field uses
1264 // itself in its initializer.
1265 Diag(L, diag::warn_field_is_uninit);
1266 }
1267 }
1268
Eli Friedman59c04372009-07-29 19:44:27 +00001269 bool HasDependentArg = false;
1270 for (unsigned i = 0; i < NumArgs; i++)
1271 HasDependentArg |= Args[i]->isTypeDependent();
1272
Eli Friedman59c04372009-07-29 19:44:27 +00001273 QualType FieldType = Member->getType();
1274 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1275 FieldType = Array->getElementType();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001276 if (FieldType->isDependentType() || HasDependentArg) {
1277 // Can't check initialization for a member of dependent type or when
1278 // any of the arguments are type-dependent expressions.
1279 OwningExprResult Init
1280 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1281 RParenLoc));
1282
1283 // Erase any temporaries within this evaluation context; we're not
1284 // going to track them in the AST, since we'll be rebuilding the
1285 // ASTs during template instantiation.
1286 ExprTemporaries.erase(
1287 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1288 ExprTemporaries.end());
1289
1290 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1291 LParenLoc,
1292 Init.takeAs<Expr>(),
1293 RParenLoc);
1294
Douglas Gregor7ad83902008-11-05 04:29:56 +00001295 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001296
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001297 if (Member->isInvalidDecl())
1298 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001299
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001300 // Initialize the member.
1301 InitializedEntity MemberEntity =
1302 InitializedEntity::InitializeMember(Member, 0);
1303 InitializationKind Kind =
1304 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1305
1306 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1307
1308 OwningExprResult MemberInit =
1309 InitSeq.Perform(*this, MemberEntity, Kind,
1310 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1311 if (MemberInit.isInvalid())
1312 return true;
1313
1314 // C++0x [class.base.init]p7:
1315 // The initialization of each base and member constitutes a
1316 // full-expression.
1317 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1318 if (MemberInit.isInvalid())
1319 return true;
1320
1321 // If we are in a dependent context, template instantiation will
1322 // perform this type-checking again. Just save the arguments that we
1323 // received in a ParenListExpr.
1324 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1325 // of the information that we have about the member
1326 // initializer. However, deconstructing the ASTs is a dicey process,
1327 // and this approach is far more likely to get the corner cases right.
1328 if (CurContext->isDependentContext()) {
1329 // Bump the reference count of all of the arguments.
1330 for (unsigned I = 0; I != NumArgs; ++I)
1331 Args[I]->Retain();
1332
1333 OwningExprResult Init
1334 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1335 RParenLoc));
1336 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1337 LParenLoc,
1338 Init.takeAs<Expr>(),
1339 RParenLoc);
1340 }
1341
Douglas Gregor802ab452009-12-02 22:36:29 +00001342 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001343 LParenLoc,
1344 MemberInit.takeAs<Expr>(),
1345 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001346}
1347
1348Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001349Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001350 Expr **Args, unsigned NumArgs,
1351 SourceLocation LParenLoc, SourceLocation RParenLoc,
1352 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001353 bool HasDependentArg = false;
1354 for (unsigned i = 0; i < NumArgs; i++)
1355 HasDependentArg |= Args[i]->isTypeDependent();
1356
John McCalla93c9342009-12-07 02:54:59 +00001357 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001358 if (BaseType->isDependentType() || HasDependentArg) {
1359 // Can't check initialization for a base of dependent type or when
1360 // any of the arguments are type-dependent expressions.
1361 OwningExprResult BaseInit
1362 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1363 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001364
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001365 // Erase any temporaries within this evaluation context; we're not
1366 // going to track them in the AST, since we'll be rebuilding the
1367 // ASTs during template instantiation.
1368 ExprTemporaries.erase(
1369 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1370 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001372 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001373 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001374 LParenLoc,
1375 BaseInit.takeAs<Expr>(),
1376 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001377 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001378
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001379 if (!BaseType->isRecordType())
1380 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1381 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1382
1383 // C++ [class.base.init]p2:
1384 // [...] Unless the mem-initializer-id names a nonstatic data
1385 // member of the constructor’s class or a direct or virtual base
1386 // of that class, the mem-initializer is ill-formed. A
1387 // mem-initializer-list can initialize a base class using any
1388 // name that denotes that base class type.
1389
1390 // Check for direct and virtual base classes.
1391 const CXXBaseSpecifier *DirectBaseSpec = 0;
1392 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1393 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1394 VirtualBaseSpec);
1395
1396 // C++ [base.class.init]p2:
1397 // If a mem-initializer-id is ambiguous because it designates both
1398 // a direct non-virtual base class and an inherited virtual base
1399 // class, the mem-initializer is ill-formed.
1400 if (DirectBaseSpec && VirtualBaseSpec)
1401 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1402 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1403 // C++ [base.class.init]p2:
1404 // Unless the mem-initializer-id names a nonstatic data membeer of the
1405 // constructor's class ot a direst or virtual base of that class, the
1406 // mem-initializer is ill-formed.
1407 if (!DirectBaseSpec && !VirtualBaseSpec)
1408 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall110acc12010-04-27 01:43:38 +00001409 << BaseType << Context.getTypeDeclType(ClassDecl)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001410 << BaseTInfo->getTypeLoc().getSourceRange();
1411
1412 CXXBaseSpecifier *BaseSpec
1413 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1414 if (!BaseSpec)
1415 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1416
1417 // Initialize the base.
1418 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001419 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001420 InitializationKind Kind =
1421 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1422
1423 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1424
1425 OwningExprResult BaseInit =
1426 InitSeq.Perform(*this, BaseEntity, Kind,
1427 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1428 if (BaseInit.isInvalid())
1429 return true;
1430
1431 // C++0x [class.base.init]p7:
1432 // The initialization of each base and member constitutes a
1433 // full-expression.
1434 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1435 if (BaseInit.isInvalid())
1436 return true;
1437
1438 // If we are in a dependent context, template instantiation will
1439 // perform this type-checking again. Just save the arguments that we
1440 // received in a ParenListExpr.
1441 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1442 // of the information that we have about the base
1443 // initializer. However, deconstructing the ASTs is a dicey process,
1444 // and this approach is far more likely to get the corner cases right.
1445 if (CurContext->isDependentContext()) {
1446 // Bump the reference count of all of the arguments.
1447 for (unsigned I = 0; I != NumArgs; ++I)
1448 Args[I]->Retain();
1449
1450 OwningExprResult Init
1451 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1452 RParenLoc));
1453 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001454 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001455 LParenLoc,
1456 Init.takeAs<Expr>(),
1457 RParenLoc);
1458 }
1459
1460 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001461 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001462 LParenLoc,
1463 BaseInit.takeAs<Expr>(),
1464 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001465}
1466
Anders Carlssone5ef7402010-04-23 03:10:23 +00001467/// ImplicitInitializerKind - How an implicit base or member initializer should
1468/// initialize its base or member.
1469enum ImplicitInitializerKind {
1470 IIK_Default,
1471 IIK_Copy,
1472 IIK_Move
1473};
1474
Anders Carlssondefefd22010-04-23 02:00:02 +00001475static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001476BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001477 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001478 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001479 bool IsInheritedVirtualBase,
1480 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001481 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001482 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1483 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001484
Anders Carlssone5ef7402010-04-23 03:10:23 +00001485 Sema::OwningExprResult BaseInit(SemaRef);
1486
1487 switch (ImplicitInitKind) {
1488 case IIK_Default: {
1489 InitializationKind InitKind
1490 = InitializationKind::CreateDefault(Constructor->getLocation());
1491 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1492 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1493 Sema::MultiExprArg(SemaRef, 0, 0));
1494 break;
1495 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001496
Anders Carlssone5ef7402010-04-23 03:10:23 +00001497 case IIK_Copy: {
1498 ParmVarDecl *Param = Constructor->getParamDecl(0);
1499 QualType ParamType = Param->getType().getNonReferenceType();
1500
1501 Expr *CopyCtorArg =
1502 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1503 SourceLocation(), ParamType, 0);
1504
Anders Carlssonc7957502010-04-24 22:02:54 +00001505 // Cast to the base class to avoid ambiguities.
Anders Carlssonc7957502010-04-24 22:02:54 +00001506 SemaRef.ImpCastExprToType(CopyCtorArg, BaseSpec->getType(),
1507 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson8f2abbc2010-04-24 22:54:32 +00001508 /*isLvalue=*/true,
1509 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonc7957502010-04-24 22:02:54 +00001510
Anders Carlssone5ef7402010-04-23 03:10:23 +00001511 InitializationKind InitKind
1512 = InitializationKind::CreateDirect(Constructor->getLocation(),
1513 SourceLocation(), SourceLocation());
1514 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1515 &CopyCtorArg, 1);
1516 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1517 Sema::MultiExprArg(SemaRef,
1518 (void**)&CopyCtorArg, 1));
1519 break;
1520 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001521
Anders Carlssone5ef7402010-04-23 03:10:23 +00001522 case IIK_Move:
1523 assert(false && "Unhandled initializer kind!");
1524 }
1525
Anders Carlsson84688f22010-04-20 23:11:20 +00001526 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1527 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001528 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001529
Anders Carlssondefefd22010-04-23 02:00:02 +00001530 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001531 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1532 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1533 SourceLocation()),
1534 BaseSpec->isVirtual(),
1535 SourceLocation(),
1536 BaseInit.takeAs<Expr>(),
1537 SourceLocation());
1538
Anders Carlssondefefd22010-04-23 02:00:02 +00001539 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001540}
1541
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001542static bool
1543BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001544 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001545 FieldDecl *Field,
1546 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001547 if (ImplicitInitKind == IIK_Copy) {
1548 ParmVarDecl *Param = Constructor->getParamDecl(0);
1549 QualType ParamType = Param->getType().getNonReferenceType();
1550
1551 Expr *MemberExprBase =
1552 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1553 SourceLocation(), ParamType, 0);
1554
1555
1556 Expr *CopyCtorArg =
1557 MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false,
1558 0, SourceRange(), Field,
1559 DeclAccessPair::make(Field, Field->getAccess()),
1560 SourceLocation(), 0,
1561 Field->getType().getNonReferenceType());
1562
1563 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1564 InitializationKind InitKind =
1565 InitializationKind::CreateDirect(Constructor->getLocation(),
1566 SourceLocation(), SourceLocation());
1567
1568 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1569 &CopyCtorArg, 1);
1570
1571 Sema::OwningExprResult MemberInit =
1572 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1573 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0);
1574 if (MemberInit.isInvalid())
1575 return true;
1576
Anders Carlssone5ef7402010-04-23 03:10:23 +00001577 CXXMemberInit = 0;
1578 return false;
1579 }
1580
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001581 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1582
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001583 QualType FieldBaseElementType =
1584 SemaRef.Context.getBaseElementType(Field->getType());
1585
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001586 if (FieldBaseElementType->isRecordType()) {
1587 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001588 InitializationKind InitKind =
1589 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001590
1591 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1592 Sema::OwningExprResult MemberInit =
1593 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1594 Sema::MultiExprArg(SemaRef, 0, 0));
1595 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1596 if (MemberInit.isInvalid())
1597 return true;
1598
1599 CXXMemberInit =
1600 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1601 Field, SourceLocation(),
1602 SourceLocation(),
1603 MemberInit.takeAs<Expr>(),
1604 SourceLocation());
1605 return false;
1606 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001607
1608 if (FieldBaseElementType->isReferenceType()) {
1609 SemaRef.Diag(Constructor->getLocation(),
1610 diag::err_uninitialized_member_in_ctor)
1611 << (int)Constructor->isImplicit()
1612 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1613 << 0 << Field->getDeclName();
1614 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1615 return true;
1616 }
1617
1618 if (FieldBaseElementType.isConstQualified()) {
1619 SemaRef.Diag(Constructor->getLocation(),
1620 diag::err_uninitialized_member_in_ctor)
1621 << (int)Constructor->isImplicit()
1622 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1623 << 1 << Field->getDeclName();
1624 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1625 return true;
1626 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001627
1628 // Nothing to initialize.
1629 CXXMemberInit = 0;
1630 return false;
1631}
1632
Eli Friedman80c30da2009-11-09 19:20:36 +00001633bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001634Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001635 CXXBaseOrMemberInitializer **Initializers,
1636 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001637 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001638 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001639 // Just store the initializers as written, they will be checked during
1640 // instantiation.
1641 if (NumInitializers > 0) {
1642 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1643 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1644 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1645 memcpy(baseOrMemberInitializers, Initializers,
1646 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1647 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1648 }
1649
1650 return false;
1651 }
1652
Anders Carlssone5ef7402010-04-23 03:10:23 +00001653 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1654
1655 // FIXME: Handle implicit move constructors.
1656 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1657 ImplicitInitKind = IIK_Copy;
1658
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001659 // We need to build the initializer AST according to order of construction
1660 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001661 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001662 if (!ClassDecl)
1663 return true;
1664
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001665 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1666 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman80c30da2009-11-09 19:20:36 +00001667 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001669 for (unsigned i = 0; i < NumInitializers; i++) {
1670 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001671
1672 if (Member->isBaseInitializer())
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001673 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001674 else
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001675 AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001676 }
1677
Anders Carlsson711f34a2010-04-21 19:52:01 +00001678 // Keep track of the direct virtual bases.
1679 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1680 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1681 E = ClassDecl->bases_end(); I != E; ++I) {
1682 if (I->isVirtual())
1683 DirectVBases.insert(I);
1684 }
1685
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001686 // Push virtual bases before others.
1687 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1688 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1689
1690 if (CXXBaseOrMemberInitializer *Value
1691 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1692 AllToInit.push_back(Value);
1693 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001694 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001695 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001696 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1697 VBase, IsInheritedVirtualBase,
1698 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001699 HadError = true;
1700 continue;
1701 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001702
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001703 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001704 }
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001707 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1708 E = ClassDecl->bases_end(); Base != E; ++Base) {
1709 // Virtuals are in the virtual base list and already constructed.
1710 if (Base->isVirtual())
1711 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001713 if (CXXBaseOrMemberInitializer *Value
1714 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1715 AllToInit.push_back(Value);
1716 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001717 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001718 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1719 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001720 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001721 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001722 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001723 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001724
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001725 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001726 }
1727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001729 // non-static data members.
1730 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1731 E = ClassDecl->field_end(); Field != E; ++Field) {
1732 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001733 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001734 Field->getType()->getAs<RecordType>()) {
1735 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001736 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001737 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001738 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1739 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1740 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1741 // set to the anonymous union data member used in the initializer
1742 // list.
1743 Value->setMember(*Field);
1744 Value->setAnonUnionMember(*FA);
1745 AllToInit.push_back(Value);
1746 break;
1747 }
1748 }
1749 }
1750 continue;
1751 }
1752 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1753 AllToInit.push_back(Value);
1754 continue;
1755 }
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Anders Carlssondefefd22010-04-23 02:00:02 +00001757 if (AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001758 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001759
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001760 CXXBaseOrMemberInitializer *Member;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001761 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1762 *Field, Member)) {
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001763 HadError = true;
1764 continue;
1765 }
1766
1767 // If the member doesn't need to be initialized, it will be null.
1768 if (Member)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001769 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001770 }
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001772 NumInitializers = AllToInit.size();
1773 if (NumInitializers > 0) {
1774 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1775 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1776 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallef027fe2010-03-16 21:39:52 +00001777 memcpy(baseOrMemberInitializers, AllToInit.data(),
1778 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001779 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001780
John McCallef027fe2010-03-16 21:39:52 +00001781 // Constructors implicitly reference the base and member
1782 // destructors.
1783 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1784 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001785 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001786
1787 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001788}
1789
Eli Friedman6347f422009-07-21 19:28:10 +00001790static void *GetKeyForTopLevelField(FieldDecl *Field) {
1791 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001792 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001793 if (RT->getDecl()->isAnonymousStructOrUnion())
1794 return static_cast<void *>(RT->getDecl());
1795 }
1796 return static_cast<void *>(Field);
1797}
1798
Anders Carlssonea356fb2010-04-02 05:42:15 +00001799static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1800 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001801}
1802
Anders Carlssonea356fb2010-04-02 05:42:15 +00001803static void *GetKeyForMember(ASTContext &Context,
1804 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001805 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001806 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001807 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001808
Eli Friedman6347f422009-07-21 19:28:10 +00001809 // For fields injected into the class via declaration of an anonymous union,
1810 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001811 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001813 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1814 // data member of the class. Data member used in the initializer list is
1815 // in AnonUnionMember field.
1816 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1817 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001818
John McCall3c3ccdb2010-04-10 09:28:51 +00001819 // If the field is a member of an anonymous struct or union, our key
1820 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001821 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001822 if (RD->isAnonymousStructOrUnion()) {
1823 while (true) {
1824 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1825 if (Parent->isAnonymousStructOrUnion())
1826 RD = Parent;
1827 else
1828 break;
1829 }
1830
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001831 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001832 }
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001834 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001835}
1836
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001837static void
1838DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001839 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001840 CXXBaseOrMemberInitializer **Inits,
1841 unsigned NumInits) {
1842 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001843 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
John McCalld6ca8da2010-04-10 07:37:23 +00001845 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1846 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001847 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001848
John McCalld6ca8da2010-04-10 07:37:23 +00001849 // Build the list of bases and members in the order that they'll
1850 // actually be initialized. The explicit initializers should be in
1851 // this same order but may be missing things.
1852 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Anders Carlsson071d6102010-04-02 03:38:04 +00001854 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1855
John McCalld6ca8da2010-04-10 07:37:23 +00001856 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001857 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001858 ClassDecl->vbases_begin(),
1859 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00001860 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001861
John McCalld6ca8da2010-04-10 07:37:23 +00001862 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001863 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001864 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001865 if (Base->isVirtual())
1866 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00001867 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001868 }
Mike Stump1eb44332009-09-09 15:08:12 +00001869
John McCalld6ca8da2010-04-10 07:37:23 +00001870 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001871 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1872 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00001873 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001874
John McCalld6ca8da2010-04-10 07:37:23 +00001875 unsigned NumIdealInits = IdealInitKeys.size();
1876 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00001877
John McCalld6ca8da2010-04-10 07:37:23 +00001878 CXXBaseOrMemberInitializer *PrevInit = 0;
1879 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1880 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1881 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1882
1883 // Scan forward to try to find this initializer in the idealized
1884 // initializers list.
1885 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1886 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001887 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001888
1889 // If we didn't find this initializer, it must be because we
1890 // scanned past it on a previous iteration. That can only
1891 // happen if we're out of order; emit a warning.
1892 if (IdealIndex == NumIdealInits) {
1893 assert(PrevInit && "initializer not found in initializer list");
1894
1895 Sema::SemaDiagnosticBuilder D =
1896 SemaRef.Diag(PrevInit->getSourceLocation(),
1897 diag::warn_initializer_out_of_order);
1898
1899 if (PrevInit->isMemberInitializer())
1900 D << 0 << PrevInit->getMember()->getDeclName();
1901 else
1902 D << 1 << PrevInit->getBaseClassInfo()->getType();
1903
1904 if (Init->isMemberInitializer())
1905 D << 0 << Init->getMember()->getDeclName();
1906 else
1907 D << 1 << Init->getBaseClassInfo()->getType();
1908
1909 // Move back to the initializer's location in the ideal list.
1910 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1911 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001912 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001913
1914 assert(IdealIndex != NumIdealInits &&
1915 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001916 }
John McCalld6ca8da2010-04-10 07:37:23 +00001917
1918 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001919 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001920}
1921
John McCall3c3ccdb2010-04-10 09:28:51 +00001922namespace {
1923bool CheckRedundantInit(Sema &S,
1924 CXXBaseOrMemberInitializer *Init,
1925 CXXBaseOrMemberInitializer *&PrevInit) {
1926 if (!PrevInit) {
1927 PrevInit = Init;
1928 return false;
1929 }
1930
1931 if (FieldDecl *Field = Init->getMember())
1932 S.Diag(Init->getSourceLocation(),
1933 diag::err_multiple_mem_initialization)
1934 << Field->getDeclName()
1935 << Init->getSourceRange();
1936 else {
1937 Type *BaseClass = Init->getBaseClass();
1938 assert(BaseClass && "neither field nor base");
1939 S.Diag(Init->getSourceLocation(),
1940 diag::err_multiple_base_initialization)
1941 << QualType(BaseClass, 0)
1942 << Init->getSourceRange();
1943 }
1944 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
1945 << 0 << PrevInit->getSourceRange();
1946
1947 return true;
1948}
1949
1950typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
1951typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
1952
1953bool CheckRedundantUnionInit(Sema &S,
1954 CXXBaseOrMemberInitializer *Init,
1955 RedundantUnionMap &Unions) {
1956 FieldDecl *Field = Init->getMember();
1957 RecordDecl *Parent = Field->getParent();
1958 if (!Parent->isAnonymousStructOrUnion())
1959 return false;
1960
1961 NamedDecl *Child = Field;
1962 do {
1963 if (Parent->isUnion()) {
1964 UnionEntry &En = Unions[Parent];
1965 if (En.first && En.first != Child) {
1966 S.Diag(Init->getSourceLocation(),
1967 diag::err_multiple_mem_union_initialization)
1968 << Field->getDeclName()
1969 << Init->getSourceRange();
1970 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
1971 << 0 << En.second->getSourceRange();
1972 return true;
1973 } else if (!En.first) {
1974 En.first = Child;
1975 En.second = Init;
1976 }
1977 }
1978
1979 Child = Parent;
1980 Parent = cast<RecordDecl>(Parent->getDeclContext());
1981 } while (Parent->isAnonymousStructOrUnion());
1982
1983 return false;
1984}
1985}
1986
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001987/// ActOnMemInitializers - Handle the member initializers for a constructor.
1988void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1989 SourceLocation ColonLoc,
1990 MemInitTy **meminits, unsigned NumMemInits,
1991 bool AnyErrors) {
1992 if (!ConstructorDecl)
1993 return;
1994
1995 AdjustDeclIfTemplate(ConstructorDecl);
1996
1997 CXXConstructorDecl *Constructor
1998 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1999
2000 if (!Constructor) {
2001 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2002 return;
2003 }
2004
2005 CXXBaseOrMemberInitializer **MemInits =
2006 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002007
2008 // Mapping for the duplicate initializers check.
2009 // For member initializers, this is keyed with a FieldDecl*.
2010 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002011 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002012
2013 // Mapping for the inconsistent anonymous-union initializers check.
2014 RedundantUnionMap MemberUnions;
2015
Anders Carlssonea356fb2010-04-02 05:42:15 +00002016 bool HadError = false;
2017 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002018 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002019
John McCall3c3ccdb2010-04-10 09:28:51 +00002020 if (Init->isMemberInitializer()) {
2021 FieldDecl *Field = Init->getMember();
2022 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2023 CheckRedundantUnionInit(*this, Init, MemberUnions))
2024 HadError = true;
2025 } else {
2026 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2027 if (CheckRedundantInit(*this, Init, Members[Key]))
2028 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002029 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002030 }
2031
Anders Carlssonea356fb2010-04-02 05:42:15 +00002032 if (HadError)
2033 return;
2034
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002035 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002036
2037 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002038}
2039
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002040void
John McCallef027fe2010-03-16 21:39:52 +00002041Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2042 CXXRecordDecl *ClassDecl) {
2043 // Ignore dependent contexts.
2044 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002045 return;
John McCall58e6f342010-03-16 05:22:47 +00002046
2047 // FIXME: all the access-control diagnostics are positioned on the
2048 // field/base declaration. That's probably good; that said, the
2049 // user might reasonably want to know why the destructor is being
2050 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002051
Anders Carlsson9f853df2009-11-17 04:44:12 +00002052 // Non-static data members.
2053 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2054 E = ClassDecl->field_end(); I != E; ++I) {
2055 FieldDecl *Field = *I;
2056
2057 QualType FieldType = Context.getBaseElementType(Field->getType());
2058
2059 const RecordType* RT = FieldType->getAs<RecordType>();
2060 if (!RT)
2061 continue;
2062
2063 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2064 if (FieldClassDecl->hasTrivialDestructor())
2065 continue;
2066
John McCall58e6f342010-03-16 05:22:47 +00002067 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2068 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002069 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002070 << Field->getDeclName()
2071 << FieldType);
2072
John McCallef027fe2010-03-16 21:39:52 +00002073 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002074 }
2075
John McCall58e6f342010-03-16 05:22:47 +00002076 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2077
Anders Carlsson9f853df2009-11-17 04:44:12 +00002078 // Bases.
2079 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2080 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002081 // Bases are always records in a well-formed non-dependent class.
2082 const RecordType *RT = Base->getType()->getAs<RecordType>();
2083
2084 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002085 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002086 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002087
2088 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002089 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002090 if (BaseClassDecl->hasTrivialDestructor())
2091 continue;
John McCall58e6f342010-03-16 05:22:47 +00002092
2093 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2094
2095 // FIXME: caret should be on the start of the class name
2096 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002097 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002098 << Base->getType()
2099 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002100
John McCallef027fe2010-03-16 21:39:52 +00002101 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002102 }
2103
2104 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002105 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2106 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002107
2108 // Bases are always records in a well-formed non-dependent class.
2109 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2110
2111 // Ignore direct virtual bases.
2112 if (DirectVirtualBases.count(RT))
2113 continue;
2114
Anders Carlsson9f853df2009-11-17 04:44:12 +00002115 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002116 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002117 if (BaseClassDecl->hasTrivialDestructor())
2118 continue;
John McCall58e6f342010-03-16 05:22:47 +00002119
2120 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2121 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002122 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002123 << VBase->getType());
2124
John McCallef027fe2010-03-16 21:39:52 +00002125 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002126 }
2127}
2128
Fariborz Jahanian393612e2009-07-21 22:36:06 +00002129void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002130 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002131 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Mike Stump1eb44332009-09-09 15:08:12 +00002133 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00002134 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002135 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002136}
2137
Mike Stump1eb44332009-09-09 15:08:12 +00002138bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002139 unsigned DiagID, AbstractDiagSelID SelID,
2140 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002141 if (SelID == -1)
2142 return RequireNonAbstractType(Loc, T,
2143 PDiag(DiagID), CurrentRD);
2144 else
2145 return RequireNonAbstractType(Loc, T,
2146 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002147}
2148
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002149bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2150 const PartialDiagnostic &PD,
2151 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002152 if (!getLangOptions().CPlusPlus)
2153 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Anders Carlsson11f21a02009-03-23 19:10:31 +00002155 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002156 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002157 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenek6217b802009-07-29 21:53:49 +00002159 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002160 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002161 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002162 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002164 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002165 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002166 }
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenek6217b802009-07-29 21:53:49 +00002168 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002169 if (!RT)
2170 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
John McCall86ff3082010-02-04 22:26:26 +00002172 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002173
Anders Carlssone65a3c82009-03-24 17:23:42 +00002174 if (CurrentRD && CurrentRD != RD)
2175 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002176
John McCall86ff3082010-02-04 22:26:26 +00002177 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002178 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002179 return false;
2180
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002181 if (!RD->isAbstract())
2182 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002184 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002186 // Check if we've already emitted the list of pure virtual functions for this
2187 // class.
2188 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2189 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002191 CXXFinalOverriderMap FinalOverriders;
2192 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002194 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2195 MEnd = FinalOverriders.end();
2196 M != MEnd;
2197 ++M) {
2198 for (OverridingMethods::iterator SO = M->second.begin(),
2199 SOEnd = M->second.end();
2200 SO != SOEnd; ++SO) {
2201 // C++ [class.abstract]p4:
2202 // A class is abstract if it contains or inherits at least one
2203 // pure virtual function for which the final overrider is pure
2204 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002206 //
2207 if (SO->second.size() != 1)
2208 continue;
2209
2210 if (!SO->second.front().Method->isPure())
2211 continue;
2212
2213 Diag(SO->second.front().Method->getLocation(),
2214 diag::note_pure_virtual_function)
2215 << SO->second.front().Method->getDeclName();
2216 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002217 }
2218
2219 if (!PureVirtualClassDiagSet)
2220 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2221 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002223 return true;
2224}
2225
Anders Carlsson8211eff2009-03-24 01:19:16 +00002226namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002227 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002228 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2229 Sema &SemaRef;
2230 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Anders Carlssone65a3c82009-03-24 17:23:42 +00002232 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002233 bool Invalid = false;
2234
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002235 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2236 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002237 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002238
Anders Carlsson8211eff2009-03-24 01:19:16 +00002239 return Invalid;
2240 }
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Anders Carlssone65a3c82009-03-24 17:23:42 +00002242 public:
2243 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2244 : SemaRef(SemaRef), AbstractClass(ac) {
2245 Visit(SemaRef.Context.getTranslationUnitDecl());
2246 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002247
Anders Carlssone65a3c82009-03-24 17:23:42 +00002248 bool VisitFunctionDecl(const FunctionDecl *FD) {
2249 if (FD->isThisDeclarationADefinition()) {
2250 // No need to do the check if we're in a definition, because it requires
2251 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002252 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002253 return VisitDeclContext(FD);
2254 }
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Anders Carlssone65a3c82009-03-24 17:23:42 +00002256 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002257 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002258 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002259 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2260 diag::err_abstract_type_in_decl,
2261 Sema::AbstractReturnType,
2262 AbstractClass);
2263
Mike Stump1eb44332009-09-09 15:08:12 +00002264 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002265 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002266 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002267 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002268 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002269 VD->getOriginalType(),
2270 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002271 Sema::AbstractParamType,
2272 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002273 }
2274
2275 return Invalid;
2276 }
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Anders Carlssone65a3c82009-03-24 17:23:42 +00002278 bool VisitDecl(const Decl* D) {
2279 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2280 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Anders Carlssone65a3c82009-03-24 17:23:42 +00002282 return false;
2283 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002284 };
2285}
2286
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002287/// \brief Perform semantic checks on a class definition that has been
2288/// completing, introducing implicitly-declared members, checking for
2289/// abstract types, etc.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002290void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002291 if (!Record || Record->isInvalidDecl())
2292 return;
2293
Eli Friedmanff2d8782009-12-16 20:00:27 +00002294 if (!Record->isDependentType())
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002295 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002296
Eli Friedmanff2d8782009-12-16 20:00:27 +00002297 if (Record->isInvalidDecl())
2298 return;
2299
John McCall233a6412010-01-28 07:38:46 +00002300 // Set access bits correctly on the directly-declared conversions.
2301 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2302 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2303 Convs->setAccess(I, (*I)->getAccess());
2304
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002305 // Determine whether we need to check for final overriders. We do
2306 // this either when there are virtual base classes (in which case we
2307 // may end up finding multiple final overriders for a given virtual
2308 // function) or any of the base classes is abstract (in which case
2309 // we might detect that this class is abstract).
2310 bool CheckFinalOverriders = false;
2311 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2312 !Record->isDependentType()) {
2313 if (Record->getNumVBases())
2314 CheckFinalOverriders = true;
2315 else if (!Record->isAbstract()) {
2316 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2317 BEnd = Record->bases_end();
2318 B != BEnd; ++B) {
2319 CXXRecordDecl *BaseDecl
2320 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2321 if (BaseDecl->isAbstract()) {
2322 CheckFinalOverriders = true;
2323 break;
2324 }
2325 }
2326 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002327 }
2328
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002329 if (CheckFinalOverriders) {
2330 CXXFinalOverriderMap FinalOverriders;
2331 Record->getFinalOverriders(FinalOverriders);
2332
2333 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2334 MEnd = FinalOverriders.end();
2335 M != MEnd; ++M) {
2336 for (OverridingMethods::iterator SO = M->second.begin(),
2337 SOEnd = M->second.end();
2338 SO != SOEnd; ++SO) {
2339 assert(SO->second.size() > 0 &&
2340 "All virtual functions have overridding virtual functions");
2341 if (SO->second.size() == 1) {
2342 // C++ [class.abstract]p4:
2343 // A class is abstract if it contains or inherits at least one
2344 // pure virtual function for which the final overrider is pure
2345 // virtual.
2346 if (SO->second.front().Method->isPure())
2347 Record->setAbstract(true);
2348 continue;
2349 }
2350
2351 // C++ [class.virtual]p2:
2352 // In a derived class, if a virtual member function of a base
2353 // class subobject has more than one final overrider the
2354 // program is ill-formed.
2355 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2356 << (NamedDecl *)M->first << Record;
2357 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2358 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2359 OMEnd = SO->second.end();
2360 OM != OMEnd; ++OM)
2361 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2362 << (NamedDecl *)M->first << OM->Method->getParent();
2363
2364 Record->setInvalidDecl();
2365 }
2366 }
2367 }
2368
2369 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002370 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor325e5932010-04-15 00:00:53 +00002371
2372 // If this is not an aggregate type and has no user-declared constructor,
2373 // complain about any non-static data members of reference or const scalar
2374 // type, since they will never get initializers.
2375 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2376 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2377 bool Complained = false;
2378 for (RecordDecl::field_iterator F = Record->field_begin(),
2379 FEnd = Record->field_end();
2380 F != FEnd; ++F) {
2381 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002382 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002383 if (!Complained) {
2384 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2385 << Record->getTagKind() << Record;
2386 Complained = true;
2387 }
2388
2389 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2390 << F->getType()->isReferenceType()
2391 << F->getDeclName();
2392 }
2393 }
2394 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002395}
2396
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002397void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002398 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002399 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002400 SourceLocation RBrac,
2401 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002402 if (!TagDecl)
2403 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Douglas Gregor42af25f2009-05-11 19:58:34 +00002405 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002406
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002407 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002408 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002409 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002410
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002411 CheckCompletedCXXClass(S,
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002412 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002413}
2414
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002415/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2416/// special functions, such as the default constructor, copy
2417/// constructor, or destructor, to the given C++ class (C++
2418/// [special]p1). This routine can only be executed just before the
2419/// definition of the class is complete.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002420///
2421/// The scope, if provided, is the class scope.
2422void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2423 CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002424 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002425 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002426
Sebastian Redl465226e2009-05-27 22:11:52 +00002427 // FIXME: Implicit declarations have exception specifications, which are
2428 // the union of the specifications of the implicitly called functions.
2429
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002430 if (!ClassDecl->hasUserDeclaredConstructor()) {
2431 // C++ [class.ctor]p5:
2432 // A default constructor for a class X is a constructor of class X
2433 // that can be called without an argument. If there is no
2434 // user-declared constructor for class X, a default constructor is
2435 // implicitly declared. An implicitly-declared default constructor
2436 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002437 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002438 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002439 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002440 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002441 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002442 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002443 0, 0, false, 0,
2444 /*FIXME*/false, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002445 0, 0,
2446 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002447 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002448 /*isExplicit=*/false,
2449 /*isInline=*/true,
2450 /*isImplicitlyDeclared=*/true);
2451 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002452 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002453 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002454 if (S)
2455 PushOnScopeChains(DefaultCon, S, true);
2456 else
2457 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002458 }
2459
2460 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2461 // C++ [class.copy]p4:
2462 // If the class definition does not explicitly declare a copy
2463 // constructor, one is declared implicitly.
2464
2465 // C++ [class.copy]p5:
2466 // The implicitly-declared copy constructor for a class X will
2467 // have the form
2468 //
2469 // X::X(const X&)
2470 //
2471 // if
2472 bool HasConstCopyConstructor = true;
2473
2474 // -- each direct or virtual base class B of X has a copy
2475 // constructor whose first parameter is of type const B& or
2476 // const volatile B&, and
2477 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2478 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2479 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002480 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002481 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002482 = BaseClassDecl->hasConstCopyConstructor(Context);
2483 }
2484
2485 // -- for all the nonstatic data members of X that are of a
2486 // class type M (or array thereof), each such class type
2487 // has a copy constructor whose first parameter is of type
2488 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002489 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2490 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002491 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002492 QualType FieldType = (*Field)->getType();
2493 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2494 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002495 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002496 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002497 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002498 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002499 = FieldClassDecl->hasConstCopyConstructor(Context);
2500 }
2501 }
2502
Sebastian Redl64b45f72009-01-05 20:52:13 +00002503 // Otherwise, the implicitly declared copy constructor will have
2504 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002505 //
2506 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002507 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002508 if (HasConstCopyConstructor)
2509 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002510 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002511
Sebastian Redl64b45f72009-01-05 20:52:13 +00002512 // An implicitly-declared copy constructor is an inline public
2513 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002514 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002515 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002516 CXXConstructorDecl *CopyConstructor
2517 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002518 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002519 Context.getFunctionType(Context.VoidTy,
2520 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002521 false, 0,
2522 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002523 false, 0, 0,
2524 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002525 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002526 /*isExplicit=*/false,
2527 /*isInline=*/true,
2528 /*isImplicitlyDeclared=*/true);
2529 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002530 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002531 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002532
2533 // Add the parameter to the constructor.
2534 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2535 ClassDecl->getLocation(),
2536 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002537 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002538 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002539 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002540 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002541 if (S)
2542 PushOnScopeChains(CopyConstructor, S, true);
2543 else
2544 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002545 }
2546
Sebastian Redl64b45f72009-01-05 20:52:13 +00002547 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2548 // Note: The following rules are largely analoguous to the copy
2549 // constructor rules. Note that virtual bases are not taken into account
2550 // for determining the argument type of the operator. Note also that
2551 // operators taking an object instead of a reference are allowed.
2552 //
2553 // C++ [class.copy]p10:
2554 // If the class definition does not explicitly declare a copy
2555 // assignment operator, one is declared implicitly.
2556 // The implicitly-defined copy assignment operator for a class X
2557 // will have the form
2558 //
2559 // X& X::operator=(const X&)
2560 //
2561 // if
2562 bool HasConstCopyAssignment = true;
2563
2564 // -- each direct base class B of X has a copy assignment operator
2565 // whose parameter is of type const B&, const volatile B& or B,
2566 // and
2567 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2568 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002569 assert(!Base->getType()->isDependentType() &&
2570 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002571 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002572 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002573 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002574 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002575 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002576 }
2577
2578 // -- for all the nonstatic data members of X that are of a class
2579 // type M (or array thereof), each such class type has a copy
2580 // assignment operator whose parameter is of type const M&,
2581 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002582 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2583 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002584 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002585 QualType FieldType = (*Field)->getType();
2586 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2587 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002588 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002589 const CXXRecordDecl *FieldClassDecl
2590 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002591 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002592 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002593 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002594 }
2595 }
2596
2597 // Otherwise, the implicitly declared copy assignment operator will
2598 // have the form
2599 //
2600 // X& X::operator=(X&)
2601 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002602 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002603 if (HasConstCopyAssignment)
2604 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002605 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002606
2607 // An implicitly-declared copy assignment operator is an inline public
2608 // member of its class.
2609 DeclarationName Name =
2610 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2611 CXXMethodDecl *CopyAssignment =
2612 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2613 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002614 false, 0,
2615 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002616 false, 0, 0,
2617 FunctionType::ExtInfo()),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002618 /*TInfo=*/0, /*isStatic=*/false,
2619 /*StorageClassAsWritten=*/FunctionDecl::None,
2620 /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002621 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002622 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002623 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002624 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002625
2626 // Add the parameter to the operator.
2627 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2628 ClassDecl->getLocation(),
2629 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002630 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002631 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002632 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002633 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002634
2635 // Don't call addedAssignmentOperator. There is no way to distinguish an
2636 // implicit from an explicit assignment operator.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002637 if (S)
2638 PushOnScopeChains(CopyAssignment, S, true);
2639 else
2640 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002641 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002642 }
2643
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002644 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002645 // C++ [class.dtor]p2:
2646 // If a class has no user-declared destructor, a destructor is
2647 // declared implicitly. An implicitly-declared destructor is an
2648 // inline public member of its class.
John McCall21ef0fa2010-03-11 09:03:00 +00002649 QualType Ty = Context.getFunctionType(Context.VoidTy,
2650 0, 0, false, 0,
2651 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002652 false, 0, 0, FunctionType::ExtInfo());
John McCall21ef0fa2010-03-11 09:03:00 +00002653
Mike Stump1eb44332009-09-09 15:08:12 +00002654 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002655 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002656 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002657 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall21ef0fa2010-03-11 09:03:00 +00002658 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002659 /*isInline=*/true,
2660 /*isImplicitlyDeclared=*/true);
2661 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002662 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002663 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002664 if (S)
2665 PushOnScopeChains(Destructor, S, true);
2666 else
2667 ClassDecl->addDecl(Destructor);
John McCall21ef0fa2010-03-11 09:03:00 +00002668
2669 // This could be uniqued if it ever proves significant.
2670 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlssond5a942b2009-11-26 21:25:09 +00002671
2672 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002673 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002674}
2675
Douglas Gregor6569d682009-05-27 23:11:45 +00002676void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002677 Decl *D = TemplateD.getAs<Decl>();
2678 if (!D)
2679 return;
2680
2681 TemplateParameterList *Params = 0;
2682 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2683 Params = Template->getTemplateParameters();
2684 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2685 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2686 Params = PartialSpec->getTemplateParameters();
2687 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002688 return;
2689
Douglas Gregor6569d682009-05-27 23:11:45 +00002690 for (TemplateParameterList::iterator Param = Params->begin(),
2691 ParamEnd = Params->end();
2692 Param != ParamEnd; ++Param) {
2693 NamedDecl *Named = cast<NamedDecl>(*Param);
2694 if (Named->getDeclName()) {
2695 S->AddDecl(DeclPtrTy::make(Named));
2696 IdResolver.AddDecl(Named);
2697 }
2698 }
2699}
2700
John McCall7a1dc562009-12-19 10:49:29 +00002701void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2702 if (!RecordD) return;
2703 AdjustDeclIfTemplate(RecordD);
2704 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2705 PushDeclContext(S, Record);
2706}
2707
2708void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2709 if (!RecordD) return;
2710 PopDeclContext();
2711}
2712
Douglas Gregor72b505b2008-12-16 21:30:33 +00002713/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2714/// parsing a top-level (non-nested) C++ class, and we are now
2715/// parsing those parts of the given Method declaration that could
2716/// not be parsed earlier (C++ [class.mem]p2), such as default
2717/// arguments. This action should enter the scope of the given
2718/// Method declaration as if we had just parsed the qualified method
2719/// name. However, it should not bring the parameters into scope;
2720/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002721void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002722}
2723
2724/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2725/// C++ method declaration. We're (re-)introducing the given
2726/// function parameter into scope for use in parsing later parts of
2727/// the method declaration. For example, we could see an
2728/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002729void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002730 if (!ParamD)
2731 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Chris Lattnerb28317a2009-03-28 19:18:32 +00002733 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002734
2735 // If this parameter has an unparsed default argument, clear it out
2736 // to make way for the parsed default argument.
2737 if (Param->hasUnparsedDefaultArg())
2738 Param->setDefaultArg(0);
2739
Chris Lattnerb28317a2009-03-28 19:18:32 +00002740 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002741 if (Param->getDeclName())
2742 IdResolver.AddDecl(Param);
2743}
2744
2745/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2746/// processing the delayed method declaration for Method. The method
2747/// declaration is now considered finished. There may be a separate
2748/// ActOnStartOfFunctionDef action later (not necessarily
2749/// immediately!) for this method, if it was also defined inside the
2750/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002751void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002752 if (!MethodD)
2753 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002755 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Chris Lattnerb28317a2009-03-28 19:18:32 +00002757 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002758
2759 // Now that we have our default arguments, check the constructor
2760 // again. It could produce additional diagnostics or affect whether
2761 // the class has implicitly-declared destructors, among other
2762 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002763 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2764 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002765
2766 // Check the default arguments, which we may have added.
2767 if (!Method->isInvalidDecl())
2768 CheckCXXDefaultArguments(Method);
2769}
2770
Douglas Gregor42a552f2008-11-05 20:51:48 +00002771/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002772/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002773/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002774/// emit diagnostics and set the invalid bit to true. In any case, the type
2775/// will be updated to reflect a well-formed type for the constructor and
2776/// returned.
2777QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2778 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002779 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002780
2781 // C++ [class.ctor]p3:
2782 // A constructor shall not be virtual (10.3) or static (9.4). A
2783 // constructor can be invoked for a const, volatile or const
2784 // volatile object. A constructor shall not be declared const,
2785 // volatile, or const volatile (9.3.2).
2786 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002787 if (!D.isInvalidType())
2788 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2789 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2790 << SourceRange(D.getIdentifierLoc());
2791 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002792 }
2793 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002794 if (!D.isInvalidType())
2795 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2796 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2797 << SourceRange(D.getIdentifierLoc());
2798 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002799 SC = FunctionDecl::None;
2800 }
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattner65401802009-04-25 08:28:21 +00002802 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2803 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002804 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002805 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2806 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002807 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002808 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2809 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002810 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002811 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2812 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002813 }
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Douglas Gregor42a552f2008-11-05 20:51:48 +00002815 // Rebuild the function type "R" without any type qualifiers (in
2816 // case any of the errors above fired) and with "void" as the
2817 // return type, since constructors don't have return types. We
2818 // *always* have to do this, because GetTypeForDeclarator will
2819 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002820 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002821 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2822 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002823 Proto->isVariadic(), 0,
2824 Proto->hasExceptionSpec(),
2825 Proto->hasAnyExceptionSpec(),
2826 Proto->getNumExceptions(),
2827 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002828 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002829}
2830
Douglas Gregor72b505b2008-12-16 21:30:33 +00002831/// CheckConstructor - Checks a fully-formed constructor for
2832/// well-formedness, issuing any diagnostics required. Returns true if
2833/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002834void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002835 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002836 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2837 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002838 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002839
2840 // C++ [class.copy]p3:
2841 // A declaration of a constructor for a class X is ill-formed if
2842 // its first parameter is of type (optionally cv-qualified) X and
2843 // either there are no other parameters or else all other
2844 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002845 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002846 ((Constructor->getNumParams() == 1) ||
2847 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002848 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2849 Constructor->getTemplateSpecializationKind()
2850 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002851 QualType ParamType = Constructor->getParamDecl(0)->getType();
2852 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2853 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002854 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2855 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor849b2432010-03-31 17:46:05 +00002856 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002857
2858 // FIXME: Rather that making the constructor invalid, we should endeavor
2859 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002860 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002861 }
2862 }
Mike Stump1eb44332009-09-09 15:08:12 +00002863
John McCall3d043362010-04-13 07:45:41 +00002864 // Notify the class that we've added a constructor. In principle we
2865 // don't need to do this for out-of-line declarations; in practice
2866 // we only instantiate the most recent declaration of a method, so
2867 // we have to call this for everything but friends.
2868 if (!Constructor->getFriendObjectKind())
2869 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002870}
2871
Anders Carlsson37909802009-11-30 21:24:50 +00002872/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2873/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002874bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002875 CXXRecordDecl *RD = Destructor->getParent();
2876
2877 if (Destructor->isVirtual()) {
2878 SourceLocation Loc;
2879
2880 if (!Destructor->isImplicit())
2881 Loc = Destructor->getLocation();
2882 else
2883 Loc = RD->getLocation();
2884
2885 // If we have a virtual destructor, look up the deallocation function
2886 FunctionDecl *OperatorDelete = 0;
2887 DeclarationName Name =
2888 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002889 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002890 return true;
2891
2892 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002893 }
Anders Carlsson37909802009-11-30 21:24:50 +00002894
2895 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002896}
2897
Mike Stump1eb44332009-09-09 15:08:12 +00002898static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002899FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2900 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2901 FTI.ArgInfo[0].Param &&
2902 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2903}
2904
Douglas Gregor42a552f2008-11-05 20:51:48 +00002905/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2906/// the well-formednes of the destructor declarator @p D with type @p
2907/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002908/// emit diagnostics and set the declarator to invalid. Even if this happens,
2909/// will be updated to reflect a well-formed type for the destructor and
2910/// returned.
2911QualType Sema::CheckDestructorDeclarator(Declarator &D,
2912 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002913 // C++ [class.dtor]p1:
2914 // [...] A typedef-name that names a class is a class-name
2915 // (7.1.3); however, a typedef-name that names a class shall not
2916 // be used as the identifier in the declarator for a destructor
2917 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002918 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002919 if (isa<TypedefType>(DeclaratorType)) {
2920 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002921 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002922 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002923 }
2924
2925 // C++ [class.dtor]p2:
2926 // A destructor is used to destroy objects of its class type. A
2927 // destructor takes no parameters, and no return type can be
2928 // specified for it (not even void). The address of a destructor
2929 // shall not be taken. A destructor shall not be static. A
2930 // destructor can be invoked for a const, volatile or const
2931 // volatile object. A destructor shall not be declared const,
2932 // volatile or const volatile (9.3.2).
2933 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002934 if (!D.isInvalidType())
2935 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2936 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2937 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002938 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002939 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002940 }
Chris Lattner65401802009-04-25 08:28:21 +00002941 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002942 // Destructors don't have return types, but the parser will
2943 // happily parse something like:
2944 //
2945 // class X {
2946 // float ~X();
2947 // };
2948 //
2949 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002950 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2951 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2952 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002953 }
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Chris Lattner65401802009-04-25 08:28:21 +00002955 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2956 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002957 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002958 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2959 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002960 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002961 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2962 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002963 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002964 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2965 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002966 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002967 }
2968
2969 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002970 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002971 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2972
2973 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002974 FTI.freeArgs();
2975 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002976 }
2977
Mike Stump1eb44332009-09-09 15:08:12 +00002978 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002979 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002980 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002981 D.setInvalidType();
2982 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002983
2984 // Rebuild the function type "R" without any type qualifiers or
2985 // parameters (in case any of the errors above fired) and with
2986 // "void" as the return type, since destructors don't have return
2987 // types. We *always* have to do this, because GetTypeForDeclarator
2988 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002989 // FIXME: Exceptions!
2990 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002991 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002992}
2993
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002994/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2995/// well-formednes of the conversion function declarator @p D with
2996/// type @p R. If there are any errors in the declarator, this routine
2997/// will emit diagnostics and return true. Otherwise, it will return
2998/// false. Either way, the type @p R will be updated to reflect a
2999/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003000void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003001 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003002 // C++ [class.conv.fct]p1:
3003 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003004 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003005 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003006 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003007 if (!D.isInvalidType())
3008 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3009 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3010 << SourceRange(D.getIdentifierLoc());
3011 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003012 SC = FunctionDecl::None;
3013 }
John McCalla3f81372010-04-13 00:04:31 +00003014
3015 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3016
Chris Lattner6e475012009-04-25 08:35:12 +00003017 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003018 // Conversion functions don't have return types, but the parser will
3019 // happily parse something like:
3020 //
3021 // class X {
3022 // float operator bool();
3023 // };
3024 //
3025 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003026 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3027 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3028 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003029 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003030 }
3031
John McCalla3f81372010-04-13 00:04:31 +00003032 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3033
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003034 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003035 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003036 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3037
3038 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003039 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003040 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003041 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003042 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003043 D.setInvalidType();
3044 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003045
John McCalla3f81372010-04-13 00:04:31 +00003046 // Diagnose "&operator bool()" and other such nonsense. This
3047 // is actually a gcc extension which we don't support.
3048 if (Proto->getResultType() != ConvType) {
3049 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3050 << Proto->getResultType();
3051 D.setInvalidType();
3052 ConvType = Proto->getResultType();
3053 }
3054
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003055 // C++ [class.conv.fct]p4:
3056 // The conversion-type-id shall not represent a function type nor
3057 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003058 if (ConvType->isArrayType()) {
3059 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3060 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003061 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003062 } else if (ConvType->isFunctionType()) {
3063 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3064 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003065 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003066 }
3067
3068 // Rebuild the function type "R" without any parameters (in case any
3069 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003070 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003071 if (D.isInvalidType()) {
3072 R = Context.getFunctionType(ConvType, 0, 0, false,
3073 Proto->getTypeQuals(),
3074 Proto->hasExceptionSpec(),
3075 Proto->hasAnyExceptionSpec(),
3076 Proto->getNumExceptions(),
3077 Proto->exception_begin(),
3078 Proto->getExtInfo());
3079 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003080
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003081 // C++0x explicit conversion operators.
3082 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003083 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003084 diag::warn_explicit_conversion_functions)
3085 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003086}
3087
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003088/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3089/// the declaration of the given C++ conversion function. This routine
3090/// is responsible for recording the conversion function in the C++
3091/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003092Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003093 assert(Conversion && "Expected to receive a conversion function declaration");
3094
Douglas Gregor9d350972008-12-12 08:25:50 +00003095 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003096
3097 // Make sure we aren't redeclaring the conversion function.
3098 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003099
3100 // C++ [class.conv.fct]p1:
3101 // [...] A conversion function is never used to convert a
3102 // (possibly cv-qualified) object to the (possibly cv-qualified)
3103 // same object type (or a reference to it), to a (possibly
3104 // cv-qualified) base class of that type (or a reference to it),
3105 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003106 // FIXME: Suppress this warning if the conversion function ends up being a
3107 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003108 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003109 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003110 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003111 ConvType = ConvTypeRef->getPointeeType();
3112 if (ConvType->isRecordType()) {
3113 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3114 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003115 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003116 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003117 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003118 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003119 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003120 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003121 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003122 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003123 }
3124
Douglas Gregor48026d22010-01-11 18:40:55 +00003125 if (Conversion->getPrimaryTemplate()) {
3126 // ignore specializations
3127 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003128 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003129 = Conversion->getDescribedFunctionTemplate()) {
3130 if (ClassDecl->replaceConversion(
3131 ConversionTemplate->getPreviousDeclaration(),
3132 ConversionTemplate))
3133 return DeclPtrTy::make(ConversionTemplate);
3134 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3135 Conversion))
John McCallba135432009-11-21 08:51:07 +00003136 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00003137 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003138 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003139 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003140 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003141 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003142 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003143
Chris Lattnerb28317a2009-03-28 19:18:32 +00003144 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003145}
3146
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003147//===----------------------------------------------------------------------===//
3148// Namespace Handling
3149//===----------------------------------------------------------------------===//
3150
3151/// ActOnStartNamespaceDef - This is called at the start of a namespace
3152/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003153Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3154 SourceLocation IdentLoc,
3155 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003156 SourceLocation LBrace,
3157 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003158 NamespaceDecl *Namespc =
3159 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3160 Namespc->setLBracLoc(LBrace);
3161
3162 Scope *DeclRegionScope = NamespcScope->getParent();
3163
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003164 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3165
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003166 if (II) {
3167 // C++ [namespace.def]p2:
3168 // The identifier in an original-namespace-definition shall not have been
3169 // previously defined in the declarative region in which the
3170 // original-namespace-definition appears. The identifier in an
3171 // original-namespace-definition is the name of the namespace. Subsequently
3172 // in that declarative region, it is treated as an original-namespace-name.
3173
John McCallf36e02d2009-10-09 21:13:30 +00003174 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003175 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003176 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Douglas Gregor44b43212008-12-11 16:49:14 +00003178 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3179 // This is an extended namespace definition.
3180 // Attach this namespace decl to the chain of extended namespace
3181 // definitions.
3182 OrigNS->setNextNamespace(Namespc);
3183 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003184
Mike Stump1eb44332009-09-09 15:08:12 +00003185 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003186 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003187 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003188 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003189 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003190 } else if (PrevDecl) {
3191 // This is an invalid name redefinition.
3192 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3193 << Namespc->getDeclName();
3194 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3195 Namespc->setInvalidDecl();
3196 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003197 } else if (II->isStr("std") &&
3198 CurContext->getLookupContext()->isTranslationUnit()) {
3199 // This is the first "real" definition of the namespace "std", so update
3200 // our cache of the "std" namespace to point at this definition.
3201 if (StdNamespace) {
3202 // We had already defined a dummy namespace "std". Link this new
3203 // namespace definition to the dummy namespace "std".
3204 StdNamespace->setNextNamespace(Namespc);
3205 StdNamespace->setLocation(IdentLoc);
3206 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3207 }
3208
3209 // Make our StdNamespace cache point at the first real definition of the
3210 // "std" namespace.
3211 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003212 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003213
3214 PushOnScopeChains(Namespc, DeclRegionScope);
3215 } else {
John McCall9aeed322009-10-01 00:25:31 +00003216 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003217 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003218
3219 // Link the anonymous namespace into its parent.
3220 NamespaceDecl *PrevDecl;
3221 DeclContext *Parent = CurContext->getLookupContext();
3222 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3223 PrevDecl = TU->getAnonymousNamespace();
3224 TU->setAnonymousNamespace(Namespc);
3225 } else {
3226 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3227 PrevDecl = ND->getAnonymousNamespace();
3228 ND->setAnonymousNamespace(Namespc);
3229 }
3230
3231 // Link the anonymous namespace with its previous declaration.
3232 if (PrevDecl) {
3233 assert(PrevDecl->isAnonymousNamespace());
3234 assert(!PrevDecl->getNextNamespace());
3235 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3236 PrevDecl->setNextNamespace(Namespc);
3237 }
John McCall9aeed322009-10-01 00:25:31 +00003238
Douglas Gregora4181472010-03-24 00:46:35 +00003239 CurContext->addDecl(Namespc);
3240
John McCall9aeed322009-10-01 00:25:31 +00003241 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3242 // behaves as if it were replaced by
3243 // namespace unique { /* empty body */ }
3244 // using namespace unique;
3245 // namespace unique { namespace-body }
3246 // where all occurrences of 'unique' in a translation unit are
3247 // replaced by the same identifier and this identifier differs
3248 // from all other identifiers in the entire program.
3249
3250 // We just create the namespace with an empty name and then add an
3251 // implicit using declaration, just like the standard suggests.
3252 //
3253 // CodeGen enforces the "universally unique" aspect by giving all
3254 // declarations semantically contained within an anonymous
3255 // namespace internal linkage.
3256
John McCall5fdd7642009-12-16 02:06:49 +00003257 if (!PrevDecl) {
3258 UsingDirectiveDecl* UD
3259 = UsingDirectiveDecl::Create(Context, CurContext,
3260 /* 'using' */ LBrace,
3261 /* 'namespace' */ SourceLocation(),
3262 /* qualifier */ SourceRange(),
3263 /* NNS */ NULL,
3264 /* identifier */ SourceLocation(),
3265 Namespc,
3266 /* Ancestor */ CurContext);
3267 UD->setImplicit();
3268 CurContext->addDecl(UD);
3269 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003270 }
3271
3272 // Although we could have an invalid decl (i.e. the namespace name is a
3273 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003274 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3275 // for the namespace has the declarations that showed up in that particular
3276 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003277 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003278 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003279}
3280
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003281/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3282/// is a namespace alias, returns the namespace it points to.
3283static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3284 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3285 return AD->getNamespace();
3286 return dyn_cast_or_null<NamespaceDecl>(D);
3287}
3288
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003289/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3290/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003291void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3292 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003293 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3294 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3295 Namespc->setRBracLoc(RBrace);
3296 PopDeclContext();
3297}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003298
Chris Lattnerb28317a2009-03-28 19:18:32 +00003299Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3300 SourceLocation UsingLoc,
3301 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003302 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003303 SourceLocation IdentLoc,
3304 IdentifierInfo *NamespcName,
3305 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003306 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3307 assert(NamespcName && "Invalid NamespcName.");
3308 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003309 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003310
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003311 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003312
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003313 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003314 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3315 LookupParsedName(R, S, &SS);
3316 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003317 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003318
John McCallf36e02d2009-10-09 21:13:30 +00003319 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003320 NamedDecl *Named = R.getFoundDecl();
3321 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3322 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003323 // C++ [namespace.udir]p1:
3324 // A using-directive specifies that the names in the nominated
3325 // namespace can be used in the scope in which the
3326 // using-directive appears after the using-directive. During
3327 // unqualified name lookup (3.4.1), the names appear as if they
3328 // were declared in the nearest enclosing namespace which
3329 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003330 // namespace. [Note: in this context, "contains" means "contains
3331 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003332
3333 // Find enclosing context containing both using-directive and
3334 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003335 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003336 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3337 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3338 CommonAncestor = CommonAncestor->getParent();
3339
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003340 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003341 SS.getRange(),
3342 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003343 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003344 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003345 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003346 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003347 }
3348
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003349 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003350 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003351 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003352}
3353
3354void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3355 // If scope has associated entity, then using directive is at namespace
3356 // or translation unit scope. We add UsingDirectiveDecls, into
3357 // it's lookup structure.
3358 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003359 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003360 else
3361 // Otherwise it is block-sope. using-directives will affect lookup
3362 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003363 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003364}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003365
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003366
3367Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003368 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003369 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003370 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003371 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003372 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003373 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003374 bool IsTypeName,
3375 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003376 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Douglas Gregor12c118a2009-11-04 16:30:06 +00003378 switch (Name.getKind()) {
3379 case UnqualifiedId::IK_Identifier:
3380 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003381 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003382 case UnqualifiedId::IK_ConversionFunctionId:
3383 break;
3384
3385 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003386 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003387 // C++0x inherited constructors.
3388 if (getLangOptions().CPlusPlus0x) break;
3389
Douglas Gregor12c118a2009-11-04 16:30:06 +00003390 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3391 << SS.getRange();
3392 return DeclPtrTy();
3393
3394 case UnqualifiedId::IK_DestructorName:
3395 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3396 << SS.getRange();
3397 return DeclPtrTy();
3398
3399 case UnqualifiedId::IK_TemplateId:
3400 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3401 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3402 return DeclPtrTy();
3403 }
3404
3405 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003406 if (!TargetName)
3407 return DeclPtrTy();
3408
John McCall60fa3cf2009-12-11 02:10:03 +00003409 // Warn about using declarations.
3410 // TODO: store that the declaration was written without 'using' and
3411 // talk about access decls instead of using decls in the
3412 // diagnostics.
3413 if (!HasUsingKeyword) {
3414 UsingLoc = Name.getSourceRange().getBegin();
3415
3416 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003417 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003418 }
3419
John McCall9488ea12009-11-17 05:59:44 +00003420 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003421 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003422 TargetName, AttrList,
3423 /* IsInstantiation */ false,
3424 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003425 if (UD)
3426 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Anders Carlssonc72160b2009-08-28 05:40:36 +00003428 return DeclPtrTy::make(UD);
3429}
3430
John McCall9f54ad42009-12-10 09:41:52 +00003431/// Determines whether to create a using shadow decl for a particular
3432/// decl, given the set of decls existing prior to this using lookup.
3433bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3434 const LookupResult &Previous) {
3435 // Diagnose finding a decl which is not from a base class of the
3436 // current class. We do this now because there are cases where this
3437 // function will silently decide not to build a shadow decl, which
3438 // will pre-empt further diagnostics.
3439 //
3440 // We don't need to do this in C++0x because we do the check once on
3441 // the qualifier.
3442 //
3443 // FIXME: diagnose the following if we care enough:
3444 // struct A { int foo; };
3445 // struct B : A { using A::foo; };
3446 // template <class T> struct C : A {};
3447 // template <class T> struct D : C<T> { using B::foo; } // <---
3448 // This is invalid (during instantiation) in C++03 because B::foo
3449 // resolves to the using decl in B, which is not a base class of D<T>.
3450 // We can't diagnose it immediately because C<T> is an unknown
3451 // specialization. The UsingShadowDecl in D<T> then points directly
3452 // to A::foo, which will look well-formed when we instantiate.
3453 // The right solution is to not collapse the shadow-decl chain.
3454 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3455 DeclContext *OrigDC = Orig->getDeclContext();
3456
3457 // Handle enums and anonymous structs.
3458 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3459 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3460 while (OrigRec->isAnonymousStructOrUnion())
3461 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3462
3463 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3464 if (OrigDC == CurContext) {
3465 Diag(Using->getLocation(),
3466 diag::err_using_decl_nested_name_specifier_is_current_class)
3467 << Using->getNestedNameRange();
3468 Diag(Orig->getLocation(), diag::note_using_decl_target);
3469 return true;
3470 }
3471
3472 Diag(Using->getNestedNameRange().getBegin(),
3473 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3474 << Using->getTargetNestedNameDecl()
3475 << cast<CXXRecordDecl>(CurContext)
3476 << Using->getNestedNameRange();
3477 Diag(Orig->getLocation(), diag::note_using_decl_target);
3478 return true;
3479 }
3480 }
3481
3482 if (Previous.empty()) return false;
3483
3484 NamedDecl *Target = Orig;
3485 if (isa<UsingShadowDecl>(Target))
3486 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3487
John McCalld7533ec2009-12-11 02:33:26 +00003488 // If the target happens to be one of the previous declarations, we
3489 // don't have a conflict.
3490 //
3491 // FIXME: but we might be increasing its access, in which case we
3492 // should redeclare it.
3493 NamedDecl *NonTag = 0, *Tag = 0;
3494 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3495 I != E; ++I) {
3496 NamedDecl *D = (*I)->getUnderlyingDecl();
3497 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3498 return false;
3499
3500 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3501 }
3502
John McCall9f54ad42009-12-10 09:41:52 +00003503 if (Target->isFunctionOrFunctionTemplate()) {
3504 FunctionDecl *FD;
3505 if (isa<FunctionTemplateDecl>(Target))
3506 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3507 else
3508 FD = cast<FunctionDecl>(Target);
3509
3510 NamedDecl *OldDecl = 0;
3511 switch (CheckOverload(FD, Previous, OldDecl)) {
3512 case Ovl_Overload:
3513 return false;
3514
3515 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003516 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003517 break;
3518
3519 // We found a decl with the exact signature.
3520 case Ovl_Match:
3521 if (isa<UsingShadowDecl>(OldDecl)) {
3522 // Silently ignore the possible conflict.
3523 return false;
3524 }
3525
3526 // If we're in a record, we want to hide the target, so we
3527 // return true (without a diagnostic) to tell the caller not to
3528 // build a shadow decl.
3529 if (CurContext->isRecord())
3530 return true;
3531
3532 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003533 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003534 break;
3535 }
3536
3537 Diag(Target->getLocation(), diag::note_using_decl_target);
3538 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3539 return true;
3540 }
3541
3542 // Target is not a function.
3543
John McCall9f54ad42009-12-10 09:41:52 +00003544 if (isa<TagDecl>(Target)) {
3545 // No conflict between a tag and a non-tag.
3546 if (!Tag) return false;
3547
John McCall41ce66f2009-12-10 19:51:03 +00003548 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003549 Diag(Target->getLocation(), diag::note_using_decl_target);
3550 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3551 return true;
3552 }
3553
3554 // No conflict between a tag and a non-tag.
3555 if (!NonTag) return false;
3556
John McCall41ce66f2009-12-10 19:51:03 +00003557 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003558 Diag(Target->getLocation(), diag::note_using_decl_target);
3559 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3560 return true;
3561}
3562
John McCall9488ea12009-11-17 05:59:44 +00003563/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003564UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003565 UsingDecl *UD,
3566 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003567
3568 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003569 NamedDecl *Target = Orig;
3570 if (isa<UsingShadowDecl>(Target)) {
3571 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3572 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003573 }
3574
3575 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003576 = UsingShadowDecl::Create(Context, CurContext,
3577 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003578 UD->addShadowDecl(Shadow);
3579
3580 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003581 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003582 else
John McCall604e7f12009-12-08 07:46:18 +00003583 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003584 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003585
John McCall32daa422010-03-31 01:36:47 +00003586 // Register it as a conversion if appropriate.
3587 if (Shadow->getDeclName().getNameKind()
3588 == DeclarationName::CXXConversionFunctionName)
3589 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3590
John McCall604e7f12009-12-08 07:46:18 +00003591 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3592 Shadow->setInvalidDecl();
3593
John McCall9f54ad42009-12-10 09:41:52 +00003594 return Shadow;
3595}
John McCall604e7f12009-12-08 07:46:18 +00003596
John McCall9f54ad42009-12-10 09:41:52 +00003597/// Hides a using shadow declaration. This is required by the current
3598/// using-decl implementation when a resolvable using declaration in a
3599/// class is followed by a declaration which would hide or override
3600/// one or more of the using decl's targets; for example:
3601///
3602/// struct Base { void foo(int); };
3603/// struct Derived : Base {
3604/// using Base::foo;
3605/// void foo(int);
3606/// };
3607///
3608/// The governing language is C++03 [namespace.udecl]p12:
3609///
3610/// When a using-declaration brings names from a base class into a
3611/// derived class scope, member functions in the derived class
3612/// override and/or hide member functions with the same name and
3613/// parameter types in a base class (rather than conflicting).
3614///
3615/// There are two ways to implement this:
3616/// (1) optimistically create shadow decls when they're not hidden
3617/// by existing declarations, or
3618/// (2) don't create any shadow decls (or at least don't make them
3619/// visible) until we've fully parsed/instantiated the class.
3620/// The problem with (1) is that we might have to retroactively remove
3621/// a shadow decl, which requires several O(n) operations because the
3622/// decl structures are (very reasonably) not designed for removal.
3623/// (2) avoids this but is very fiddly and phase-dependent.
3624void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003625 if (Shadow->getDeclName().getNameKind() ==
3626 DeclarationName::CXXConversionFunctionName)
3627 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3628
John McCall9f54ad42009-12-10 09:41:52 +00003629 // Remove it from the DeclContext...
3630 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003631
John McCall9f54ad42009-12-10 09:41:52 +00003632 // ...and the scope, if applicable...
3633 if (S) {
3634 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3635 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003636 }
3637
John McCall9f54ad42009-12-10 09:41:52 +00003638 // ...and the using decl.
3639 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3640
3641 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003642 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003643}
3644
John McCall7ba107a2009-11-18 02:36:19 +00003645/// Builds a using declaration.
3646///
3647/// \param IsInstantiation - Whether this call arises from an
3648/// instantiation of an unresolved using declaration. We treat
3649/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003650NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3651 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003652 CXXScopeSpec &SS,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003653 SourceLocation IdentLoc,
3654 DeclarationName Name,
3655 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003656 bool IsInstantiation,
3657 bool IsTypeName,
3658 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003659 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3660 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003661
Anders Carlsson550b14b2009-08-28 05:49:21 +00003662 // FIXME: We ignore attributes for now.
3663 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003665 if (SS.isEmpty()) {
3666 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003667 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003668 }
Mike Stump1eb44332009-09-09 15:08:12 +00003669
John McCall9f54ad42009-12-10 09:41:52 +00003670 // Do the redeclaration lookup in the current scope.
3671 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3672 ForRedeclaration);
3673 Previous.setHideTags(false);
3674 if (S) {
3675 LookupName(Previous, S);
3676
3677 // It is really dumb that we have to do this.
3678 LookupResult::Filter F = Previous.makeFilter();
3679 while (F.hasNext()) {
3680 NamedDecl *D = F.next();
3681 if (!isDeclInScope(D, CurContext, S))
3682 F.erase();
3683 }
3684 F.done();
3685 } else {
3686 assert(IsInstantiation && "no scope in non-instantiation");
3687 assert(CurContext->isRecord() && "scope not record in instantiation");
3688 LookupQualifiedName(Previous, CurContext);
3689 }
3690
Mike Stump1eb44332009-09-09 15:08:12 +00003691 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003692 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3693
John McCall9f54ad42009-12-10 09:41:52 +00003694 // Check for invalid redeclarations.
3695 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3696 return 0;
3697
3698 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003699 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3700 return 0;
3701
John McCallaf8e6ed2009-11-12 03:15:40 +00003702 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003703 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003704 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003705 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003706 // FIXME: not all declaration name kinds are legal here
3707 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3708 UsingLoc, TypenameLoc,
3709 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003710 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003711 } else {
3712 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3713 UsingLoc, SS.getRange(), NNS,
3714 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003715 }
John McCalled976492009-12-04 22:46:56 +00003716 } else {
3717 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3718 SS.getRange(), UsingLoc, NNS, Name,
3719 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003720 }
John McCalled976492009-12-04 22:46:56 +00003721 D->setAccess(AS);
3722 CurContext->addDecl(D);
3723
3724 if (!LookupContext) return D;
3725 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003726
John McCall77bb1aa2010-05-01 00:40:08 +00003727 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003728 UD->setInvalidDecl();
3729 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003730 }
3731
John McCall604e7f12009-12-08 07:46:18 +00003732 // Look up the target name.
3733
John McCalla24dc2e2009-11-17 02:14:36 +00003734 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003735
John McCall604e7f12009-12-08 07:46:18 +00003736 // Unlike most lookups, we don't always want to hide tag
3737 // declarations: tag names are visible through the using declaration
3738 // even if hidden by ordinary names, *except* in a dependent context
3739 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003740 if (!IsInstantiation)
3741 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003742
John McCalla24dc2e2009-11-17 02:14:36 +00003743 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003744
John McCallf36e02d2009-10-09 21:13:30 +00003745 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003746 Diag(IdentLoc, diag::err_no_member)
3747 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003748 UD->setInvalidDecl();
3749 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003750 }
3751
John McCalled976492009-12-04 22:46:56 +00003752 if (R.isAmbiguous()) {
3753 UD->setInvalidDecl();
3754 return UD;
3755 }
Mike Stump1eb44332009-09-09 15:08:12 +00003756
John McCall7ba107a2009-11-18 02:36:19 +00003757 if (IsTypeName) {
3758 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003759 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003760 Diag(IdentLoc, diag::err_using_typename_non_type);
3761 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3762 Diag((*I)->getUnderlyingDecl()->getLocation(),
3763 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003764 UD->setInvalidDecl();
3765 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003766 }
3767 } else {
3768 // If we asked for a non-typename and we got a type, error out,
3769 // but only if this is an instantiation of an unresolved using
3770 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003771 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003772 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3773 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003774 UD->setInvalidDecl();
3775 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003776 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003777 }
3778
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003779 // C++0x N2914 [namespace.udecl]p6:
3780 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003781 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003782 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3783 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003784 UD->setInvalidDecl();
3785 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003786 }
Mike Stump1eb44332009-09-09 15:08:12 +00003787
John McCall9f54ad42009-12-10 09:41:52 +00003788 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3789 if (!CheckUsingShadowDecl(UD, *I, Previous))
3790 BuildUsingShadowDecl(S, UD, *I);
3791 }
John McCall9488ea12009-11-17 05:59:44 +00003792
3793 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003794}
3795
John McCall9f54ad42009-12-10 09:41:52 +00003796/// Checks that the given using declaration is not an invalid
3797/// redeclaration. Note that this is checking only for the using decl
3798/// itself, not for any ill-formedness among the UsingShadowDecls.
3799bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3800 bool isTypeName,
3801 const CXXScopeSpec &SS,
3802 SourceLocation NameLoc,
3803 const LookupResult &Prev) {
3804 // C++03 [namespace.udecl]p8:
3805 // C++0x [namespace.udecl]p10:
3806 // A using-declaration is a declaration and can therefore be used
3807 // repeatedly where (and only where) multiple declarations are
3808 // allowed.
3809 // That's only in file contexts.
3810 if (CurContext->getLookupContext()->isFileContext())
3811 return false;
3812
3813 NestedNameSpecifier *Qual
3814 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3815
3816 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3817 NamedDecl *D = *I;
3818
3819 bool DTypename;
3820 NestedNameSpecifier *DQual;
3821 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3822 DTypename = UD->isTypeName();
3823 DQual = UD->getTargetNestedNameDecl();
3824 } else if (UnresolvedUsingValueDecl *UD
3825 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3826 DTypename = false;
3827 DQual = UD->getTargetNestedNameSpecifier();
3828 } else if (UnresolvedUsingTypenameDecl *UD
3829 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3830 DTypename = true;
3831 DQual = UD->getTargetNestedNameSpecifier();
3832 } else continue;
3833
3834 // using decls differ if one says 'typename' and the other doesn't.
3835 // FIXME: non-dependent using decls?
3836 if (isTypeName != DTypename) continue;
3837
3838 // using decls differ if they name different scopes (but note that
3839 // template instantiation can cause this check to trigger when it
3840 // didn't before instantiation).
3841 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3842 Context.getCanonicalNestedNameSpecifier(DQual))
3843 continue;
3844
3845 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003846 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003847 return true;
3848 }
3849
3850 return false;
3851}
3852
John McCall604e7f12009-12-08 07:46:18 +00003853
John McCalled976492009-12-04 22:46:56 +00003854/// Checks that the given nested-name qualifier used in a using decl
3855/// in the current context is appropriately related to the current
3856/// scope. If an error is found, diagnoses it and returns true.
3857bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3858 const CXXScopeSpec &SS,
3859 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003860 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003861
John McCall604e7f12009-12-08 07:46:18 +00003862 if (!CurContext->isRecord()) {
3863 // C++03 [namespace.udecl]p3:
3864 // C++0x [namespace.udecl]p8:
3865 // A using-declaration for a class member shall be a member-declaration.
3866
3867 // If we weren't able to compute a valid scope, it must be a
3868 // dependent class scope.
3869 if (!NamedContext || NamedContext->isRecord()) {
3870 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3871 << SS.getRange();
3872 return true;
3873 }
3874
3875 // Otherwise, everything is known to be fine.
3876 return false;
3877 }
3878
3879 // The current scope is a record.
3880
3881 // If the named context is dependent, we can't decide much.
3882 if (!NamedContext) {
3883 // FIXME: in C++0x, we can diagnose if we can prove that the
3884 // nested-name-specifier does not refer to a base class, which is
3885 // still possible in some cases.
3886
3887 // Otherwise we have to conservatively report that things might be
3888 // okay.
3889 return false;
3890 }
3891
3892 if (!NamedContext->isRecord()) {
3893 // Ideally this would point at the last name in the specifier,
3894 // but we don't have that level of source info.
3895 Diag(SS.getRange().getBegin(),
3896 diag::err_using_decl_nested_name_specifier_is_not_class)
3897 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3898 return true;
3899 }
3900
3901 if (getLangOptions().CPlusPlus0x) {
3902 // C++0x [namespace.udecl]p3:
3903 // In a using-declaration used as a member-declaration, the
3904 // nested-name-specifier shall name a base class of the class
3905 // being defined.
3906
3907 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3908 cast<CXXRecordDecl>(NamedContext))) {
3909 if (CurContext == NamedContext) {
3910 Diag(NameLoc,
3911 diag::err_using_decl_nested_name_specifier_is_current_class)
3912 << SS.getRange();
3913 return true;
3914 }
3915
3916 Diag(SS.getRange().getBegin(),
3917 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3918 << (NestedNameSpecifier*) SS.getScopeRep()
3919 << cast<CXXRecordDecl>(CurContext)
3920 << SS.getRange();
3921 return true;
3922 }
3923
3924 return false;
3925 }
3926
3927 // C++03 [namespace.udecl]p4:
3928 // A using-declaration used as a member-declaration shall refer
3929 // to a member of a base class of the class being defined [etc.].
3930
3931 // Salient point: SS doesn't have to name a base class as long as
3932 // lookup only finds members from base classes. Therefore we can
3933 // diagnose here only if we can prove that that can't happen,
3934 // i.e. if the class hierarchies provably don't intersect.
3935
3936 // TODO: it would be nice if "definitely valid" results were cached
3937 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3938 // need to be repeated.
3939
3940 struct UserData {
3941 llvm::DenseSet<const CXXRecordDecl*> Bases;
3942
3943 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3944 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3945 Data->Bases.insert(Base);
3946 return true;
3947 }
3948
3949 bool hasDependentBases(const CXXRecordDecl *Class) {
3950 return !Class->forallBases(collect, this);
3951 }
3952
3953 /// Returns true if the base is dependent or is one of the
3954 /// accumulated base classes.
3955 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3956 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3957 return !Data->Bases.count(Base);
3958 }
3959
3960 bool mightShareBases(const CXXRecordDecl *Class) {
3961 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3962 }
3963 };
3964
3965 UserData Data;
3966
3967 // Returns false if we find a dependent base.
3968 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3969 return false;
3970
3971 // Returns false if the class has a dependent base or if it or one
3972 // of its bases is present in the base set of the current context.
3973 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3974 return false;
3975
3976 Diag(SS.getRange().getBegin(),
3977 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3978 << (NestedNameSpecifier*) SS.getScopeRep()
3979 << cast<CXXRecordDecl>(CurContext)
3980 << SS.getRange();
3981
3982 return true;
John McCalled976492009-12-04 22:46:56 +00003983}
3984
Mike Stump1eb44332009-09-09 15:08:12 +00003985Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003986 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003987 SourceLocation AliasLoc,
3988 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003989 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003990 SourceLocation IdentLoc,
3991 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Anders Carlsson81c85c42009-03-28 23:53:49 +00003993 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003994 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3995 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003996
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003997 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003998 if (NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003999 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4000 ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004001 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004002 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004003 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004004 // FIXME: At some point, we'll want to create the (redundant)
4005 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004006 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004007 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlsson81c85c42009-03-28 23:53:49 +00004008 return DeclPtrTy();
4009 }
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004011 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4012 diag::err_redefinition_different_kind;
4013 Diag(AliasLoc, DiagID) << Alias;
4014 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004015 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004016 }
4017
John McCalla24dc2e2009-11-17 02:14:36 +00004018 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00004019 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00004020
John McCallf36e02d2009-10-09 21:13:30 +00004021 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00004022 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004023 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00004024 }
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004026 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004027 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4028 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004029 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004030 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004031
John McCall3dbd3d52010-02-16 06:53:13 +00004032 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00004033 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00004034}
4035
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004036void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4037 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004038 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4039 !Constructor->isUsed()) &&
4040 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004042 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004043 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004044
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004045 DeclContext *PreviousContext = CurContext;
4046 CurContext = Constructor;
Anders Carlssonec3332b2010-04-02 03:43:34 +00004047 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00004048 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004049 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004050 Constructor->setInvalidDecl();
4051 } else {
4052 Constructor->setUsed();
4053 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004054 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004055}
4056
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004057void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004058 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004059 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4060 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004061 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004062 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004063
4064 DeclContext *PreviousContext = CurContext;
4065 CurContext = Destructor;
4066
John McCallef027fe2010-03-16 21:39:52 +00004067 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4068 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004069
Anders Carlsson37909802009-11-30 21:24:50 +00004070 // FIXME: If CheckDestructor fails, we should emit a note about where the
4071 // implicit destructor was needed.
4072 if (CheckDestructor(Destructor)) {
4073 Diag(CurrentLocation, diag::note_member_synthesized_at)
4074 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4075
4076 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004077 CurContext = PreviousContext;
4078
Anders Carlsson37909802009-11-30 21:24:50 +00004079 return;
4080 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004081 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00004082
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004083 Destructor->setUsed();
4084}
4085
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004086void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
4087 CXXMethodDecl *MethodDecl) {
4088 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
4089 MethodDecl->getOverloadedOperator() == OO_Equal &&
4090 !MethodDecl->isUsed()) &&
4091 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004093 CXXRecordDecl *ClassDecl
4094 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004096 DeclContext *PreviousContext = CurContext;
4097 CurContext = MethodDecl;
4098
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00004099 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004100 // Before the implicitly-declared copy assignment operator for a class is
4101 // implicitly defined, all implicitly-declared copy assignment operators
4102 // for its direct base classes and its nonstatic data members shall have
4103 // been implicitly defined.
4104 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00004105 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4106 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004107 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004108 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004109 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004110 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
John McCallb0207482010-03-16 06:11:48 +00004111 BaseClassDecl)) {
4112 CheckDirectMemberAccess(Base->getSourceRange().getBegin(),
4113 BaseAssignOpMethod,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004114 PDiag(diag::err_access_assign_base)
John McCallb0207482010-03-16 06:11:48 +00004115 << Base->getType());
4116
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004117 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
John McCallb0207482010-03-16 06:11:48 +00004118 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004119 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00004120 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4121 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004122 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4123 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4124 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004125 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004126 CXXRecordDecl *FieldClassDecl
4127 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004128 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004129 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
John McCallb0207482010-03-16 06:11:48 +00004130 FieldClassDecl)) {
4131 CheckDirectMemberAccess(Field->getLocation(),
4132 FieldAssignOpMethod,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004133 PDiag(diag::err_access_assign_field)
John McCallb0207482010-03-16 06:11:48 +00004134 << Field->getDeclName() << Field->getType());
4135
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004136 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
John McCallb0207482010-03-16 06:11:48 +00004137 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004138 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004139 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00004140 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4141 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004142 Diag(CurrentLocation, diag::note_first_required_here);
4143 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004144 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004145 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00004146 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4147 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004148 Diag(CurrentLocation, diag::note_first_required_here);
4149 err = true;
4150 }
4151 }
4152 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00004153 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004154
4155 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004156}
4157
4158CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004159Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
4160 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004161 CXXRecordDecl *ClassDecl) {
4162 QualType LHSType = Context.getTypeDeclType(ClassDecl);
4163 QualType RHSType(LHSType);
4164 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00004165 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004166 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00004167 RHSType = Context.getCVRQualifiedType(RHSType,
4168 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00004169 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004170 LHSType,
4171 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00004172 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004173 RHSType,
4174 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004175 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00004176 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00004177 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004178 CandidateSet);
4179 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004180 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004181 return cast<CXXMethodDecl>(Best->Function);
4182 assert(false &&
4183 "getAssignOperatorMethod - copy assignment operator method not found");
4184 return 0;
4185}
4186
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004187void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4188 CXXConstructorDecl *CopyConstructor,
4189 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00004190 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00004191 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004192 !CopyConstructor->isUsed()) &&
4193 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Anders Carlsson63010a72010-04-23 16:24:12 +00004195 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004196 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004197
4198 DeclContext *PreviousContext = CurContext;
4199 CurContext = CopyConstructor;
4200
Anders Carlsson8e142cc2010-04-25 00:52:09 +00004201 // C++ [class.copy] p209
4202 // Before the implicitly-declared copy constructor for a class is
4203 // implicitly defined, all the implicitly-declared copy constructors
4204 // for its base class and its non-static data members shall have been
4205 // implicitly defined.
4206 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
4207 Base != ClassDecl->bases_end(); ++Base) {
4208 CXXRecordDecl *BaseClassDecl
4209 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
4210 if (CXXConstructorDecl *BaseCopyCtor =
4211 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) {
4212 CheckDirectMemberAccess(Base->getSourceRange().getBegin(),
4213 BaseCopyCtor,
4214 PDiag(diag::err_access_copy_base)
4215 << Base->getType());
Anders Carlssone127abe2010-04-24 22:25:18 +00004216
Anders Carlsson8e142cc2010-04-25 00:52:09 +00004217 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
4218 }
4219 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004220 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4221 FieldEnd = ClassDecl->field_end();
4222 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004223 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4224 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4225 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004226 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004227 CXXRecordDecl *FieldClassDecl
4228 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004229 if (CXXConstructorDecl *FieldCopyCtor =
John McCallb0207482010-03-16 06:11:48 +00004230 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4231 CheckDirectMemberAccess(Field->getLocation(),
4232 FieldCopyCtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004233 PDiag(diag::err_access_copy_field)
John McCallb0207482010-03-16 06:11:48 +00004234 << Field->getDeclName() << Field->getType());
4235
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00004236 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
John McCallb0207482010-03-16 06:11:48 +00004237 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004238 }
4239 }
4240 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004241
4242 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004243}
4244
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004245Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004246Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00004247 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00004248 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004249 bool RequiresZeroInit,
4250 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004251 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Douglas Gregor2f599792010-04-02 18:24:57 +00004253 // C++0x [class.copy]p34:
4254 // When certain criteria are met, an implementation is allowed to
4255 // omit the copy/move construction of a class object, even if the
4256 // copy/move constructor and/or destructor for the object have
4257 // side effects. [...]
4258 // - when a temporary class object that has not been bound to a
4259 // reference (12.2) would be copied/moved to a class object
4260 // with the same cv-unqualified type, the copy/move operation
4261 // can be omitted by constructing the temporary object
4262 // directly into the target of the omitted copy/move
4263 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4264 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4265 Elidable = SubExpr->isTemporaryObject() &&
4266 Context.hasSameUnqualifiedType(SubExpr->getType(),
4267 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004268 }
Mike Stump1eb44332009-09-09 15:08:12 +00004269
4270 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004271 Elidable, move(ExprArgs), RequiresZeroInit,
4272 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004273}
4274
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004275/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4276/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004277Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004278Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4279 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004280 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004281 bool RequiresZeroInit,
4282 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004283 unsigned NumExprs = ExprArgs.size();
4284 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004285
Douglas Gregor7edfb692009-11-23 12:27:39 +00004286 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004287 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004288 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004289 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004290}
4291
Mike Stump1eb44332009-09-09 15:08:12 +00004292bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004293 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004294 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004295 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004296 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004297 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004298 if (TempResult.isInvalid())
4299 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004301 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004302 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004303 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004304 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Anders Carlssonfe2de492009-08-25 05:18:00 +00004306 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004307}
4308
John McCall68c6c9a2010-02-02 09:10:11 +00004309void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4310 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004311 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4312 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004313 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4314 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00004315 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004316 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00004317 << VD->getDeclName()
4318 << VD->getType());
John McCall4f9506a2010-02-02 08:45:54 +00004319 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004320}
4321
Mike Stump1eb44332009-09-09 15:08:12 +00004322/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004323/// ActOnDeclarator, when a C++ direct initializer is present.
4324/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004325void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4326 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004327 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004328 SourceLocation *CommaLocs,
4329 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004330 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004331 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004332
4333 // If there is no declaration, there was an error parsing it. Just ignore
4334 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004335 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004336 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004337
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004338 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4339 if (!VDecl) {
4340 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4341 RealDecl->setInvalidDecl();
4342 return;
4343 }
4344
Douglas Gregor83ddad32009-08-26 21:14:46 +00004345 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004346 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004347 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4348 //
4349 // Clients that want to distinguish between the two forms, can check for
4350 // direct initializer using VarDecl::hasCXXDirectInitializer().
4351 // A major benefit is that clients that don't particularly care about which
4352 // exactly form was it (like the CodeGen) can handle both cases without
4353 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004354
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004355 // C++ 8.5p11:
4356 // The form of initialization (using parentheses or '=') is generally
4357 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004358 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004359 QualType DeclInitType = VDecl->getType();
4360 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004361 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004362
Douglas Gregor4dffad62010-02-11 22:55:30 +00004363 if (!VDecl->getType()->isDependentType() &&
4364 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004365 diag::err_typecheck_decl_incomplete_type)) {
4366 VDecl->setInvalidDecl();
4367 return;
4368 }
4369
Douglas Gregor90f93822009-12-22 22:17:25 +00004370 // The variable can not have an abstract class type.
4371 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4372 diag::err_abstract_type_in_decl,
4373 AbstractVariableType))
4374 VDecl->setInvalidDecl();
4375
Sebastian Redl31310a22010-02-01 20:16:42 +00004376 const VarDecl *Def;
4377 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004378 Diag(VDecl->getLocation(), diag::err_redefinition)
4379 << VDecl->getDeclName();
4380 Diag(Def->getLocation(), diag::note_previous_definition);
4381 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004382 return;
4383 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004384
4385 // If either the declaration has a dependent type or if any of the
4386 // expressions is type-dependent, we represent the initialization
4387 // via a ParenListExpr for later use during template instantiation.
4388 if (VDecl->getType()->isDependentType() ||
4389 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4390 // Let clients know that initialization was done with a direct initializer.
4391 VDecl->setCXXDirectInitializer(true);
4392
4393 // Store the initialization expressions as a ParenListExpr.
4394 unsigned NumExprs = Exprs.size();
4395 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4396 (Expr **)Exprs.release(),
4397 NumExprs, RParenLoc));
4398 return;
4399 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004400
4401 // Capture the variable that is being initialized and the style of
4402 // initialization.
4403 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4404
4405 // FIXME: Poor source location information.
4406 InitializationKind Kind
4407 = InitializationKind::CreateDirect(VDecl->getLocation(),
4408 LParenLoc, RParenLoc);
4409
4410 InitializationSequence InitSeq(*this, Entity, Kind,
4411 (Expr**)Exprs.get(), Exprs.size());
4412 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4413 if (Result.isInvalid()) {
4414 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004415 return;
4416 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004417
4418 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004419 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004420 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004421
John McCall68c6c9a2010-02-02 09:10:11 +00004422 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4423 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004424}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004425
Douglas Gregor39da0b82009-09-09 23:08:42 +00004426/// \brief Given a constructor and the set of arguments provided for the
4427/// constructor, convert the arguments and add any required default arguments
4428/// to form a proper call to this constructor.
4429///
4430/// \returns true if an error occurred, false otherwise.
4431bool
4432Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4433 MultiExprArg ArgsPtr,
4434 SourceLocation Loc,
4435 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4436 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4437 unsigned NumArgs = ArgsPtr.size();
4438 Expr **Args = (Expr **)ArgsPtr.get();
4439
4440 const FunctionProtoType *Proto
4441 = Constructor->getType()->getAs<FunctionProtoType>();
4442 assert(Proto && "Constructor without a prototype?");
4443 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004444
4445 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004446 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004447 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004448 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004449 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004450
4451 VariadicCallType CallType =
4452 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4453 llvm::SmallVector<Expr *, 8> AllArgs;
4454 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4455 Proto, 0, Args, NumArgs, AllArgs,
4456 CallType);
4457 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4458 ConvertedArgs.push_back(AllArgs[i]);
4459 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004460}
4461
Anders Carlsson20d45d22009-12-12 00:32:00 +00004462static inline bool
4463CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4464 const FunctionDecl *FnDecl) {
4465 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4466 if (isa<NamespaceDecl>(DC)) {
4467 return SemaRef.Diag(FnDecl->getLocation(),
4468 diag::err_operator_new_delete_declared_in_namespace)
4469 << FnDecl->getDeclName();
4470 }
4471
4472 if (isa<TranslationUnitDecl>(DC) &&
4473 FnDecl->getStorageClass() == FunctionDecl::Static) {
4474 return SemaRef.Diag(FnDecl->getLocation(),
4475 diag::err_operator_new_delete_declared_static)
4476 << FnDecl->getDeclName();
4477 }
4478
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004479 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004480}
4481
Anders Carlsson156c78e2009-12-13 17:53:43 +00004482static inline bool
4483CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4484 CanQualType ExpectedResultType,
4485 CanQualType ExpectedFirstParamType,
4486 unsigned DependentParamTypeDiag,
4487 unsigned InvalidParamTypeDiag) {
4488 QualType ResultType =
4489 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4490
4491 // Check that the result type is not dependent.
4492 if (ResultType->isDependentType())
4493 return SemaRef.Diag(FnDecl->getLocation(),
4494 diag::err_operator_new_delete_dependent_result_type)
4495 << FnDecl->getDeclName() << ExpectedResultType;
4496
4497 // Check that the result type is what we expect.
4498 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4499 return SemaRef.Diag(FnDecl->getLocation(),
4500 diag::err_operator_new_delete_invalid_result_type)
4501 << FnDecl->getDeclName() << ExpectedResultType;
4502
4503 // A function template must have at least 2 parameters.
4504 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4505 return SemaRef.Diag(FnDecl->getLocation(),
4506 diag::err_operator_new_delete_template_too_few_parameters)
4507 << FnDecl->getDeclName();
4508
4509 // The function decl must have at least 1 parameter.
4510 if (FnDecl->getNumParams() == 0)
4511 return SemaRef.Diag(FnDecl->getLocation(),
4512 diag::err_operator_new_delete_too_few_parameters)
4513 << FnDecl->getDeclName();
4514
4515 // Check the the first parameter type is not dependent.
4516 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4517 if (FirstParamType->isDependentType())
4518 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4519 << FnDecl->getDeclName() << ExpectedFirstParamType;
4520
4521 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004522 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004523 ExpectedFirstParamType)
4524 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4525 << FnDecl->getDeclName() << ExpectedFirstParamType;
4526
4527 return false;
4528}
4529
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004530static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004531CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004532 // C++ [basic.stc.dynamic.allocation]p1:
4533 // A program is ill-formed if an allocation function is declared in a
4534 // namespace scope other than global scope or declared static in global
4535 // scope.
4536 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4537 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004538
4539 CanQualType SizeTy =
4540 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4541
4542 // C++ [basic.stc.dynamic.allocation]p1:
4543 // The return type shall be void*. The first parameter shall have type
4544 // std::size_t.
4545 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4546 SizeTy,
4547 diag::err_operator_new_dependent_param_type,
4548 diag::err_operator_new_param_type))
4549 return true;
4550
4551 // C++ [basic.stc.dynamic.allocation]p1:
4552 // The first parameter shall not have an associated default argument.
4553 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004554 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004555 diag::err_operator_new_default_arg)
4556 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4557
4558 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004559}
4560
4561static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004562CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4563 // C++ [basic.stc.dynamic.deallocation]p1:
4564 // A program is ill-formed if deallocation functions are declared in a
4565 // namespace scope other than global scope or declared static in global
4566 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004567 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4568 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004569
4570 // C++ [basic.stc.dynamic.deallocation]p2:
4571 // Each deallocation function shall return void and its first parameter
4572 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004573 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4574 SemaRef.Context.VoidPtrTy,
4575 diag::err_operator_delete_dependent_param_type,
4576 diag::err_operator_delete_param_type))
4577 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004578
Anders Carlsson46991d62009-12-12 00:16:02 +00004579 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4580 if (FirstParamType->isDependentType())
4581 return SemaRef.Diag(FnDecl->getLocation(),
4582 diag::err_operator_delete_dependent_param_type)
4583 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4584
4585 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4586 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004587 return SemaRef.Diag(FnDecl->getLocation(),
4588 diag::err_operator_delete_param_type)
4589 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004590
4591 return false;
4592}
4593
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004594/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4595/// of this overloaded operator is well-formed. If so, returns false;
4596/// otherwise, emits appropriate diagnostics and returns true.
4597bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004598 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004599 "Expected an overloaded operator declaration");
4600
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004601 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4602
Mike Stump1eb44332009-09-09 15:08:12 +00004603 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004604 // The allocation and deallocation functions, operator new,
4605 // operator new[], operator delete and operator delete[], are
4606 // described completely in 3.7.3. The attributes and restrictions
4607 // found in the rest of this subclause do not apply to them unless
4608 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004609 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004610 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004611
Anders Carlssona3ccda52009-12-12 00:26:23 +00004612 if (Op == OO_New || Op == OO_Array_New)
4613 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004614
4615 // C++ [over.oper]p6:
4616 // An operator function shall either be a non-static member
4617 // function or be a non-member function and have at least one
4618 // parameter whose type is a class, a reference to a class, an
4619 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004620 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4621 if (MethodDecl->isStatic())
4622 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004623 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004624 } else {
4625 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004626 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4627 ParamEnd = FnDecl->param_end();
4628 Param != ParamEnd; ++Param) {
4629 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004630 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4631 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004632 ClassOrEnumParam = true;
4633 break;
4634 }
4635 }
4636
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004637 if (!ClassOrEnumParam)
4638 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004639 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004640 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004641 }
4642
4643 // C++ [over.oper]p8:
4644 // An operator function cannot have default arguments (8.3.6),
4645 // except where explicitly stated below.
4646 //
Mike Stump1eb44332009-09-09 15:08:12 +00004647 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004648 // (C++ [over.call]p1).
4649 if (Op != OO_Call) {
4650 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4651 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004652 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004653 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004654 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004655 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004656 }
4657 }
4658
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004659 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4660 { false, false, false }
4661#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4662 , { Unary, Binary, MemberOnly }
4663#include "clang/Basic/OperatorKinds.def"
4664 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004665
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004666 bool CanBeUnaryOperator = OperatorUses[Op][0];
4667 bool CanBeBinaryOperator = OperatorUses[Op][1];
4668 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004669
4670 // C++ [over.oper]p8:
4671 // [...] Operator functions cannot have more or fewer parameters
4672 // than the number required for the corresponding operator, as
4673 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004674 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004675 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004676 if (Op != OO_Call &&
4677 ((NumParams == 1 && !CanBeUnaryOperator) ||
4678 (NumParams == 2 && !CanBeBinaryOperator) ||
4679 (NumParams < 1) || (NumParams > 2))) {
4680 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004681 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004682 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004683 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004684 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004685 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004686 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004687 assert(CanBeBinaryOperator &&
4688 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004689 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004690 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004691
Chris Lattner416e46f2008-11-21 07:57:12 +00004692 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004693 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004694 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004695
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004696 // Overloaded operators other than operator() cannot be variadic.
4697 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004698 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004699 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004700 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004701 }
4702
4703 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004704 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4705 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004706 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004707 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004708 }
4709
4710 // C++ [over.inc]p1:
4711 // The user-defined function called operator++ implements the
4712 // prefix and postfix ++ operator. If this function is a member
4713 // function with no parameters, or a non-member function with one
4714 // parameter of class or enumeration type, it defines the prefix
4715 // increment operator ++ for objects of that type. If the function
4716 // is a member function with one parameter (which shall be of type
4717 // int) or a non-member function with two parameters (the second
4718 // of which shall be of type int), it defines the postfix
4719 // increment operator ++ for objects of that type.
4720 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4721 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4722 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004723 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004724 ParamIsInt = BT->getKind() == BuiltinType::Int;
4725
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004726 if (!ParamIsInt)
4727 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004728 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004729 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004730 }
4731
Sebastian Redl64b45f72009-01-05 20:52:13 +00004732 // Notify the class if it got an assignment operator.
4733 if (Op == OO_Equal) {
4734 // Would have returned earlier otherwise.
4735 assert(isa<CXXMethodDecl>(FnDecl) &&
4736 "Overloaded = not member, but not filtered.");
4737 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4738 Method->getParent()->addedAssignmentOperator(Context, Method);
4739 }
4740
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004741 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004742}
Chris Lattner5a003a42008-12-17 07:09:26 +00004743
Sean Hunta6c058d2010-01-13 09:01:02 +00004744/// CheckLiteralOperatorDeclaration - Check whether the declaration
4745/// of this literal operator function is well-formed. If so, returns
4746/// false; otherwise, emits appropriate diagnostics and returns true.
4747bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4748 DeclContext *DC = FnDecl->getDeclContext();
4749 Decl::Kind Kind = DC->getDeclKind();
4750 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4751 Kind != Decl::LinkageSpec) {
4752 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4753 << FnDecl->getDeclName();
4754 return true;
4755 }
4756
4757 bool Valid = false;
4758
Sean Hunt216c2782010-04-07 23:11:06 +00004759 // template <char...> type operator "" name() is the only valid template
4760 // signature, and the only valid signature with no parameters.
4761 if (FnDecl->param_size() == 0) {
4762 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
4763 // Must have only one template parameter
4764 TemplateParameterList *Params = TpDecl->getTemplateParameters();
4765 if (Params->size() == 1) {
4766 NonTypeTemplateParmDecl *PmDecl =
4767 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00004768
Sean Hunt216c2782010-04-07 23:11:06 +00004769 // The template parameter must be a char parameter pack.
4770 // FIXME: This test will always fail because non-type parameter packs
4771 // have not been implemented.
4772 if (PmDecl && PmDecl->isTemplateParameterPack() &&
4773 Context.hasSameType(PmDecl->getType(), Context.CharTy))
4774 Valid = true;
4775 }
4776 }
4777 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00004778 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00004779 FunctionDecl::param_iterator Param = FnDecl->param_begin();
4780
Sean Hunta6c058d2010-01-13 09:01:02 +00004781 QualType T = (*Param)->getType();
4782
Sean Hunt30019c02010-04-07 22:57:35 +00004783 // unsigned long long int, long double, and any character type are allowed
4784 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00004785 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
4786 Context.hasSameType(T, Context.LongDoubleTy) ||
4787 Context.hasSameType(T, Context.CharTy) ||
4788 Context.hasSameType(T, Context.WCharTy) ||
4789 Context.hasSameType(T, Context.Char16Ty) ||
4790 Context.hasSameType(T, Context.Char32Ty)) {
4791 if (++Param == FnDecl->param_end())
4792 Valid = true;
4793 goto FinishedParams;
4794 }
4795
Sean Hunt30019c02010-04-07 22:57:35 +00004796 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00004797 const PointerType *PT = T->getAs<PointerType>();
4798 if (!PT)
4799 goto FinishedParams;
4800 T = PT->getPointeeType();
4801 if (!T.isConstQualified())
4802 goto FinishedParams;
4803 T = T.getUnqualifiedType();
4804
4805 // Move on to the second parameter;
4806 ++Param;
4807
4808 // If there is no second parameter, the first must be a const char *
4809 if (Param == FnDecl->param_end()) {
4810 if (Context.hasSameType(T, Context.CharTy))
4811 Valid = true;
4812 goto FinishedParams;
4813 }
4814
4815 // const char *, const wchar_t*, const char16_t*, and const char32_t*
4816 // are allowed as the first parameter to a two-parameter function
4817 if (!(Context.hasSameType(T, Context.CharTy) ||
4818 Context.hasSameType(T, Context.WCharTy) ||
4819 Context.hasSameType(T, Context.Char16Ty) ||
4820 Context.hasSameType(T, Context.Char32Ty)))
4821 goto FinishedParams;
4822
4823 // The second and final parameter must be an std::size_t
4824 T = (*Param)->getType().getUnqualifiedType();
4825 if (Context.hasSameType(T, Context.getSizeType()) &&
4826 ++Param == FnDecl->param_end())
4827 Valid = true;
4828 }
4829
4830 // FIXME: This diagnostic is absolutely terrible.
4831FinishedParams:
4832 if (!Valid) {
4833 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
4834 << FnDecl->getDeclName();
4835 return true;
4836 }
4837
4838 return false;
4839}
4840
Douglas Gregor074149e2009-01-05 19:45:36 +00004841/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4842/// linkage specification, including the language and (if present)
4843/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4844/// the location of the language string literal, which is provided
4845/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4846/// the '{' brace. Otherwise, this linkage specification does not
4847/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004848Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4849 SourceLocation ExternLoc,
4850 SourceLocation LangLoc,
4851 const char *Lang,
4852 unsigned StrSize,
4853 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004854 LinkageSpecDecl::LanguageIDs Language;
4855 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4856 Language = LinkageSpecDecl::lang_c;
4857 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4858 Language = LinkageSpecDecl::lang_cxx;
4859 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004860 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004861 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004862 }
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Chris Lattnercc98eac2008-12-17 07:13:27 +00004864 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Douglas Gregor074149e2009-01-05 19:45:36 +00004866 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004867 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004868 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004869 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004870 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004871 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004872}
4873
Douglas Gregor074149e2009-01-05 19:45:36 +00004874/// ActOnFinishLinkageSpecification - Completely the definition of
4875/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4876/// valid, it's the position of the closing '}' brace in a linkage
4877/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004878Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4879 DeclPtrTy LinkageSpec,
4880 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004881 if (LinkageSpec)
4882 PopDeclContext();
4883 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004884}
4885
Douglas Gregord308e622009-05-18 20:51:54 +00004886/// \brief Perform semantic analysis for the variable declaration that
4887/// occurs within a C++ catch clause, returning the newly-created
4888/// variable.
4889VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004890 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004891 IdentifierInfo *Name,
4892 SourceLocation Loc,
4893 SourceRange Range) {
4894 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004895
4896 // Arrays and functions decay.
4897 if (ExDeclType->isArrayType())
4898 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4899 else if (ExDeclType->isFunctionType())
4900 ExDeclType = Context.getPointerType(ExDeclType);
4901
4902 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4903 // The exception-declaration shall not denote a pointer or reference to an
4904 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004905 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004906 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004907 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004908 Invalid = true;
4909 }
Douglas Gregord308e622009-05-18 20:51:54 +00004910
Douglas Gregora2762912010-03-08 01:47:36 +00004911 // GCC allows catching pointers and references to incomplete types
4912 // as an extension; so do we, but we warn by default.
4913
Sebastian Redl4b07b292008-12-22 19:15:10 +00004914 QualType BaseType = ExDeclType;
4915 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004916 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00004917 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00004918 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004919 BaseType = Ptr->getPointeeType();
4920 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00004921 DK = diag::ext_catch_incomplete_ptr;
4922 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004923 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004924 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004925 BaseType = Ref->getPointeeType();
4926 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00004927 DK = diag::ext_catch_incomplete_ref;
4928 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004929 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004930 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00004931 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
4932 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00004933 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004934
Mike Stump1eb44332009-09-09 15:08:12 +00004935 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004936 RequireNonAbstractType(Loc, ExDeclType,
4937 diag::err_abstract_type_in_decl,
4938 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004939 Invalid = true;
4940
Mike Stump1eb44332009-09-09 15:08:12 +00004941 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004942 Name, ExDeclType, TInfo, VarDecl::None,
4943 VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004944
Douglas Gregor6d182892010-03-05 23:38:39 +00004945 if (!Invalid) {
4946 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
4947 // C++ [except.handle]p16:
4948 // The object declared in an exception-declaration or, if the
4949 // exception-declaration does not specify a name, a temporary (12.2) is
4950 // copy-initialized (8.5) from the exception object. [...]
4951 // The object is destroyed when the handler exits, after the destruction
4952 // of any automatic objects initialized within the handler.
4953 //
4954 // We just pretend to initialize the object with itself, then make sure
4955 // it can be destroyed later.
4956 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
4957 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
4958 Loc, ExDeclType, 0);
4959 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
4960 SourceLocation());
4961 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
4962 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4963 MultiExprArg(*this, (void**)&ExDeclRef, 1));
4964 if (Result.isInvalid())
4965 Invalid = true;
4966 else
4967 FinalizeVarWithDestructor(ExDecl, RecordTy);
4968 }
4969 }
4970
Douglas Gregord308e622009-05-18 20:51:54 +00004971 if (Invalid)
4972 ExDecl->setInvalidDecl();
4973
4974 return ExDecl;
4975}
4976
4977/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4978/// handler.
4979Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00004980 TypeSourceInfo *TInfo = 0;
4981 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004982
4983 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004984 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00004985 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00004986 LookupOrdinaryName,
4987 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004988 // The scope should be freshly made just for us. There is just no way
4989 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004990 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004991 if (PrevDecl->isTemplateParameter()) {
4992 // Maybe we will complain about the shadowed template parameter.
4993 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004994 }
4995 }
4996
Chris Lattnereaaebc72009-04-25 08:06:05 +00004997 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004998 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4999 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005000 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005001 }
5002
John McCalla93c9342009-12-07 02:54:59 +00005003 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005004 D.getIdentifier(),
5005 D.getIdentifierLoc(),
5006 D.getDeclSpec().getSourceRange());
5007
Chris Lattnereaaebc72009-04-25 08:06:05 +00005008 if (Invalid)
5009 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005010
Sebastian Redl4b07b292008-12-22 19:15:10 +00005011 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005012 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005013 PushOnScopeChains(ExDecl, S);
5014 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005015 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005016
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005017 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005018 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005019}
Anders Carlssonfb311762009-03-14 00:25:26 +00005020
Mike Stump1eb44332009-09-09 15:08:12 +00005021Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005022 ExprArg assertexpr,
5023 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005024 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005025 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005026 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5027
Anders Carlssonc3082412009-03-14 00:33:21 +00005028 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5029 llvm::APSInt Value(32);
5030 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5031 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5032 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005033 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005034 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005035
Anders Carlssonc3082412009-03-14 00:33:21 +00005036 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005037 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005038 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005039 }
5040 }
Mike Stump1eb44332009-09-09 15:08:12 +00005041
Anders Carlsson77d81422009-03-15 17:35:16 +00005042 assertexpr.release();
5043 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005044 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005045 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005046
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005047 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005048 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005049}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005050
Douglas Gregor1d869352010-04-07 16:53:43 +00005051/// \brief Perform semantic analysis of the given friend type declaration.
5052///
5053/// \returns A friend declaration that.
5054FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5055 TypeSourceInfo *TSInfo) {
5056 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5057
5058 QualType T = TSInfo->getType();
5059 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5060
Douglas Gregor06245bf2010-04-07 17:57:12 +00005061 if (!getLangOptions().CPlusPlus0x) {
5062 // C++03 [class.friend]p2:
5063 // An elaborated-type-specifier shall be used in a friend declaration
5064 // for a class.*
5065 //
5066 // * The class-key of the elaborated-type-specifier is required.
5067 if (!ActiveTemplateInstantiations.empty()) {
5068 // Do not complain about the form of friend template types during
5069 // template instantiation; we will already have complained when the
5070 // template was declared.
5071 } else if (!T->isElaboratedTypeSpecifier()) {
5072 // If we evaluated the type to a record type, suggest putting
5073 // a tag in front.
5074 if (const RecordType *RT = T->getAs<RecordType>()) {
5075 RecordDecl *RD = RT->getDecl();
5076
5077 std::string InsertionText = std::string(" ") + RD->getKindName();
5078
5079 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5080 << (unsigned) RD->getTagKind()
5081 << T
5082 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5083 InsertionText);
5084 } else {
5085 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5086 << T
5087 << SourceRange(FriendLoc, TypeRange.getEnd());
5088 }
5089 } else if (T->getAs<EnumType>()) {
5090 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00005091 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00005092 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00005093 }
5094 }
5095
Douglas Gregor06245bf2010-04-07 17:57:12 +00005096 // C++0x [class.friend]p3:
5097 // If the type specifier in a friend declaration designates a (possibly
5098 // cv-qualified) class type, that class is declared as a friend; otherwise,
5099 // the friend declaration is ignored.
5100
5101 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5102 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00005103
5104 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5105}
5106
John McCalldd4a3b02009-09-16 22:47:08 +00005107/// Handle a friend type declaration. This works in tandem with
5108/// ActOnTag.
5109///
5110/// Notes on friend class templates:
5111///
5112/// We generally treat friend class declarations as if they were
5113/// declaring a class. So, for example, the elaborated type specifier
5114/// in a friend declaration is required to obey the restrictions of a
5115/// class-head (i.e. no typedefs in the scope chain), template
5116/// parameters are required to match up with simple template-ids, &c.
5117/// However, unlike when declaring a template specialization, it's
5118/// okay to refer to a template specialization without an empty
5119/// template parameter declaration, e.g.
5120/// friend class A<T>::B<unsigned>;
5121/// We permit this as a special case; if there are any template
5122/// parameters present at all, require proper matching, i.e.
5123/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005124Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005125 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005126 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005127
5128 assert(DS.isFriendSpecified());
5129 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5130
John McCalldd4a3b02009-09-16 22:47:08 +00005131 // Try to convert the decl specifier to a type. This works for
5132 // friend templates because ActOnTag never produces a ClassTemplateDecl
5133 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005134 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall32f2fb52010-03-25 18:04:51 +00005135 TypeSourceInfo *TSI;
5136 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005137 if (TheDeclarator.isInvalidType())
5138 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005139
Douglas Gregor1d869352010-04-07 16:53:43 +00005140 if (!TSI)
5141 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5142
John McCalldd4a3b02009-09-16 22:47:08 +00005143 // This is definitely an error in C++98. It's probably meant to
5144 // be forbidden in C++0x, too, but the specification is just
5145 // poorly written.
5146 //
5147 // The problem is with declarations like the following:
5148 // template <T> friend A<T>::foo;
5149 // where deciding whether a class C is a friend or not now hinges
5150 // on whether there exists an instantiation of A that causes
5151 // 'foo' to equal C. There are restrictions on class-heads
5152 // (which we declare (by fiat) elaborated friend declarations to
5153 // be) that makes this tractable.
5154 //
5155 // FIXME: handle "template <> friend class A<T>;", which
5156 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00005157 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00005158 Diag(Loc, diag::err_tagless_friend_type_template)
5159 << DS.getSourceRange();
5160 return DeclPtrTy();
5161 }
Douglas Gregor1d869352010-04-07 16:53:43 +00005162
John McCall02cace72009-08-28 07:59:38 +00005163 // C++98 [class.friend]p1: A friend of a class is a function
5164 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005165 // This is fixed in DR77, which just barely didn't make the C++03
5166 // deadline. It's also a very silly restriction that seriously
5167 // affects inner classes and which nobody else seems to implement;
5168 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00005169 //
5170 // But note that we could warn about it: it's always useless to
5171 // friend one of your own members (it's not, however, worthless to
5172 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00005173
John McCalldd4a3b02009-09-16 22:47:08 +00005174 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00005175 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00005176 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00005177 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00005178 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00005179 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00005180 DS.getFriendSpecLoc());
5181 else
Douglas Gregor1d869352010-04-07 16:53:43 +00005182 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5183
5184 if (!D)
5185 return DeclPtrTy();
5186
John McCalldd4a3b02009-09-16 22:47:08 +00005187 D->setAccess(AS_public);
5188 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005189
John McCalldd4a3b02009-09-16 22:47:08 +00005190 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005191}
5192
John McCallbbbcdd92009-09-11 21:02:39 +00005193Sema::DeclPtrTy
5194Sema::ActOnFriendFunctionDecl(Scope *S,
5195 Declarator &D,
5196 bool IsDefinition,
5197 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005198 const DeclSpec &DS = D.getDeclSpec();
5199
5200 assert(DS.isFriendSpecified());
5201 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5202
5203 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005204 TypeSourceInfo *TInfo = 0;
5205 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005206
5207 // C++ [class.friend]p1
5208 // A friend of a class is a function or class....
5209 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005210 // It *doesn't* see through dependent types, which is correct
5211 // according to [temp.arg.type]p3:
5212 // If a declaration acquires a function type through a
5213 // type dependent on a template-parameter and this causes
5214 // a declaration that does not use the syntactic form of a
5215 // function declarator to have a function type, the program
5216 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005217 if (!T->isFunctionType()) {
5218 Diag(Loc, diag::err_unexpected_friend);
5219
5220 // It might be worthwhile to try to recover by creating an
5221 // appropriate declaration.
5222 return DeclPtrTy();
5223 }
5224
5225 // C++ [namespace.memdef]p3
5226 // - If a friend declaration in a non-local class first declares a
5227 // class or function, the friend class or function is a member
5228 // of the innermost enclosing namespace.
5229 // - The name of the friend is not found by simple name lookup
5230 // until a matching declaration is provided in that namespace
5231 // scope (either before or after the class declaration granting
5232 // friendship).
5233 // - If a friend function is called, its name may be found by the
5234 // name lookup that considers functions from namespaces and
5235 // classes associated with the types of the function arguments.
5236 // - When looking for a prior declaration of a class or a function
5237 // declared as a friend, scopes outside the innermost enclosing
5238 // namespace scope are not considered.
5239
John McCall02cace72009-08-28 07:59:38 +00005240 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5241 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005242 assert(Name);
5243
John McCall67d1a672009-08-06 02:15:43 +00005244 // The context we found the declaration in, or in which we should
5245 // create the declaration.
5246 DeclContext *DC;
5247
5248 // FIXME: handle local classes
5249
5250 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005251 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5252 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005253 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5254 DC = computeDeclContext(ScopeQual);
5255
5256 // FIXME: handle dependent contexts
5257 if (!DC) return DeclPtrTy();
John McCall77bb1aa2010-05-01 00:40:08 +00005258 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005259
John McCall68263142009-11-18 22:49:29 +00005260 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005261
5262 // If searching in that context implicitly found a declaration in
5263 // a different context, treat it like it wasn't found at all.
5264 // TODO: better diagnostics for this case. Suggesting the right
5265 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005266 // FIXME: getRepresentativeDecl() is not right here at all
5267 if (Previous.empty() ||
5268 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005269 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005270 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5271 return DeclPtrTy();
5272 }
5273
5274 // C++ [class.friend]p1: A friend of a class is a function or
5275 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005276 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005277 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5278
John McCall67d1a672009-08-06 02:15:43 +00005279 // Otherwise walk out to the nearest namespace scope looking for matches.
5280 } else {
5281 // TODO: handle local class contexts.
5282
5283 DC = CurContext;
5284 while (true) {
5285 // Skip class contexts. If someone can cite chapter and verse
5286 // for this behavior, that would be nice --- it's what GCC and
5287 // EDG do, and it seems like a reasonable intent, but the spec
5288 // really only says that checks for unqualified existing
5289 // declarations should stop at the nearest enclosing namespace,
5290 // not that they should only consider the nearest enclosing
5291 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005292 while (DC->isRecord())
5293 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005294
John McCall68263142009-11-18 22:49:29 +00005295 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005296
5297 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005298 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005299 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005300
John McCall67d1a672009-08-06 02:15:43 +00005301 if (DC->isFileContext()) break;
5302 DC = DC->getParent();
5303 }
5304
5305 // C++ [class.friend]p1: A friend of a class is a function or
5306 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005307 // C++0x changes this for both friend types and functions.
5308 // Most C++ 98 compilers do seem to give an error here, so
5309 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005310 if (!Previous.empty() && DC->Equals(CurContext)
5311 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005312 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5313 }
5314
Douglas Gregor182ddf02009-09-28 00:08:27 +00005315 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005316 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005317 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5318 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5319 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005320 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005321 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5322 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005323 return DeclPtrTy();
5324 }
John McCall67d1a672009-08-06 02:15:43 +00005325 }
5326
Douglas Gregor182ddf02009-09-28 00:08:27 +00005327 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005328 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005329 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005330 IsDefinition,
5331 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005332 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005333
Douglas Gregor182ddf02009-09-28 00:08:27 +00005334 assert(ND->getDeclContext() == DC);
5335 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005336
John McCallab88d972009-08-31 22:39:49 +00005337 // Add the function declaration to the appropriate lookup tables,
5338 // adjusting the redeclarations list as necessary. We don't
5339 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005340 //
John McCallab88d972009-08-31 22:39:49 +00005341 // Also update the scope-based lookup if the target context's
5342 // lookup context is in lexical scope.
5343 if (!CurContext->isDependentContext()) {
5344 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005345 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005346 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005347 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005348 }
John McCall02cace72009-08-28 07:59:38 +00005349
5350 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005351 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005352 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005353 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005354 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005355
Douglas Gregor182ddf02009-09-28 00:08:27 +00005356 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005357}
5358
Chris Lattnerb28317a2009-03-28 19:18:32 +00005359void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005360 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005361
Chris Lattnerb28317a2009-03-28 19:18:32 +00005362 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005363 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5364 if (!Fn) {
5365 Diag(DelLoc, diag::err_deleted_non_function);
5366 return;
5367 }
5368 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5369 Diag(DelLoc, diag::err_deleted_decl_not_first);
5370 Diag(Prev->getLocation(), diag::note_previous_declaration);
5371 // If the declaration wasn't the first, we delete the function anyway for
5372 // recovery.
5373 }
5374 Fn->setDeleted();
5375}
Sebastian Redl13e88542009-04-27 21:33:24 +00005376
5377static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5378 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5379 ++CI) {
5380 Stmt *SubStmt = *CI;
5381 if (!SubStmt)
5382 continue;
5383 if (isa<ReturnStmt>(SubStmt))
5384 Self.Diag(SubStmt->getSourceRange().getBegin(),
5385 diag::err_return_in_constructor_handler);
5386 if (!isa<Expr>(SubStmt))
5387 SearchForReturnInStmt(Self, SubStmt);
5388 }
5389}
5390
5391void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5392 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5393 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5394 SearchForReturnInStmt(*this, Handler);
5395 }
5396}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005397
Mike Stump1eb44332009-09-09 15:08:12 +00005398bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005399 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005400 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5401 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005402
Chandler Carruth73857792010-02-15 11:53:20 +00005403 if (Context.hasSameType(NewTy, OldTy) ||
5404 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005405 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005407 // Check if the return types are covariant
5408 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005409
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005410 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005411 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5412 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005413 NewClassTy = NewPT->getPointeeType();
5414 OldClassTy = OldPT->getPointeeType();
5415 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005416 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5417 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5418 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5419 NewClassTy = NewRT->getPointeeType();
5420 OldClassTy = OldRT->getPointeeType();
5421 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005422 }
5423 }
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005425 // The return types aren't either both pointers or references to a class type.
5426 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005427 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005428 diag::err_different_return_type_for_overriding_virtual_function)
5429 << New->getDeclName() << NewTy << OldTy;
5430 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005432 return true;
5433 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005434
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005435 // C++ [class.virtual]p6:
5436 // If the return type of D::f differs from the return type of B::f, the
5437 // class type in the return type of D::f shall be complete at the point of
5438 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005439 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5440 if (!RT->isBeingDefined() &&
5441 RequireCompleteType(New->getLocation(), NewClassTy,
5442 PDiag(diag::err_covariant_return_incomplete)
5443 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005444 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005445 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005446
Douglas Gregora4923eb2009-11-16 21:35:15 +00005447 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005448 // Check if the new class derives from the old class.
5449 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5450 Diag(New->getLocation(),
5451 diag::err_covariant_return_not_derived)
5452 << New->getDeclName() << NewTy << OldTy;
5453 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5454 return true;
5455 }
Mike Stump1eb44332009-09-09 15:08:12 +00005456
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005457 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00005458 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00005459 diag::err_covariant_return_inaccessible_base,
5460 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5461 // FIXME: Should this point to the return type?
5462 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005463 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5464 return true;
5465 }
5466 }
Mike Stump1eb44332009-09-09 15:08:12 +00005467
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005468 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005469 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005470 Diag(New->getLocation(),
5471 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005472 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005473 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5474 return true;
5475 };
Mike Stump1eb44332009-09-09 15:08:12 +00005476
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005477
5478 // The new class type must have the same or less qualifiers as the old type.
5479 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5480 Diag(New->getLocation(),
5481 diag::err_covariant_return_type_class_type_more_qualified)
5482 << New->getDeclName() << NewTy << OldTy;
5483 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5484 return true;
5485 };
Mike Stump1eb44332009-09-09 15:08:12 +00005486
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005487 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005488}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005489
Sean Huntbbd37c62009-11-21 08:43:09 +00005490bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5491 const CXXMethodDecl *Old)
5492{
5493 if (Old->hasAttr<FinalAttr>()) {
5494 Diag(New->getLocation(), diag::err_final_function_overridden)
5495 << New->getDeclName();
5496 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5497 return true;
5498 }
5499
5500 return false;
5501}
5502
Douglas Gregor4ba31362009-12-01 17:24:26 +00005503/// \brief Mark the given method pure.
5504///
5505/// \param Method the method to be marked pure.
5506///
5507/// \param InitRange the source range that covers the "0" initializer.
5508bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5509 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5510 Method->setPure();
5511
5512 // A class is abstract if at least one function is pure virtual.
5513 Method->getParent()->setAbstract(true);
5514 return false;
5515 }
5516
5517 if (!Method->isInvalidDecl())
5518 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5519 << Method->getDeclName() << InitRange;
5520 return true;
5521}
5522
John McCall731ad842009-12-19 09:28:58 +00005523/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5524/// an initializer for the out-of-line declaration 'Dcl'. The scope
5525/// is a fresh scope pushed for just this purpose.
5526///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005527/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5528/// static data member of class X, names should be looked up in the scope of
5529/// class X.
5530void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005531 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005532 Decl *D = Dcl.getAs<Decl>();
5533 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005534
John McCall731ad842009-12-19 09:28:58 +00005535 // We should only get called for declarations with scope specifiers, like:
5536 // int foo::bar;
5537 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005538 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005539}
5540
5541/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005542/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005543void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005544 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005545 Decl *D = Dcl.getAs<Decl>();
5546 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005547
John McCall731ad842009-12-19 09:28:58 +00005548 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005549 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005550}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005551
5552/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5553/// C++ if/switch/while/for statement.
5554/// e.g: "if (int x = f()) {...}"
5555Action::DeclResult
5556Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5557 // C++ 6.4p2:
5558 // The declarator shall not specify a function or an array.
5559 // The type-specifier-seq shall not contain typedef and shall not declare a
5560 // new class or enumeration.
5561 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5562 "Parser allowed 'typedef' as storage class of condition decl.");
5563
John McCalla93c9342009-12-07 02:54:59 +00005564 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005565 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005566 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005567
5568 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5569 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5570 // would be created and CXXConditionDeclExpr wants a VarDecl.
5571 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5572 << D.getSourceRange();
5573 return DeclResult();
5574 } else if (OwnedTag && OwnedTag->isDefinition()) {
5575 // The type-specifier-seq shall not declare a new class or enumeration.
5576 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5577 }
5578
5579 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5580 if (!Dcl)
5581 return DeclResult();
5582
5583 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5584 VD->setDeclaredInCondition(true);
5585 return Dcl;
5586}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005587
Anders Carlsson046c2942010-04-17 20:15:18 +00005588static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005589 // Ignore dependent types.
5590 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005591 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005592
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005593 // Ignore declarations that are not definitions.
5594 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005595 return false;
5596
5597 CXXRecordDecl *RD = MD->getParent();
5598
5599 // Ignore classes without a vtable.
5600 if (!RD->isDynamicClass())
5601 return false;
5602
5603 switch (MD->getParent()->getTemplateSpecializationKind()) {
5604 case TSK_Undeclared:
5605 case TSK_ExplicitSpecialization:
5606 // Classes that aren't instantiations of templates don't need their
5607 // virtual methods marked until we see the definition of the key
5608 // function.
5609 break;
5610
5611 case TSK_ImplicitInstantiation:
5612 // This is a constructor of a class template; mark all of the virtual
5613 // members as referenced to ensure that they get instantiatied.
5614 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5615 return true;
5616 break;
5617
5618 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005619 return false;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005620
5621 case TSK_ExplicitInstantiationDefinition:
5622 // This is method of a explicit instantiation; mark all of the virtual
5623 // members as referenced to ensure that they get instantiatied.
5624 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005625 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005626
5627 // Consider only out-of-line definitions of member functions. When we see
5628 // an inline definition, it's too early to compute the key function.
5629 if (!MD->isOutOfLine())
5630 return false;
5631
5632 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5633
5634 // If there is no key function, we will need a copy of the vtable.
5635 if (!KeyFunction)
5636 return true;
5637
5638 // If this is the key function, we need to mark virtual members.
5639 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5640 return true;
5641
5642 return false;
5643}
5644
5645void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5646 CXXMethodDecl *MD) {
5647 CXXRecordDecl *RD = MD->getParent();
5648
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005649 // We will need to mark all of the virtual members as referenced to build the
5650 // vtable.
Anders Carlsson046c2942010-04-17 20:15:18 +00005651 if (!needsVTable(MD, Context))
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00005652 return;
5653
5654 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5655 if (kind == TSK_ImplicitInstantiation)
5656 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5657 else
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005658 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005659}
5660
5661bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5662 if (ClassesWithUnmarkedVirtualMembers.empty())
5663 return false;
5664
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005665 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5666 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5667 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5668 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005669 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005670 }
5671
Anders Carlssond6a637f2009-12-07 08:24:59 +00005672 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005673}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005674
Rafael Espindola3e1ae932010-03-26 00:36:59 +00005675void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
5676 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00005677 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5678 e = RD->method_end(); i != e; ++i) {
5679 CXXMethodDecl *MD = *i;
5680
5681 // C++ [basic.def.odr]p2:
5682 // [...] A virtual member function is used if it is not pure. [...]
5683 if (MD->isVirtual() && !MD->isPure())
5684 MarkDeclarationReferenced(Loc, MD);
5685 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00005686
5687 // Only classes that have virtual bases need a VTT.
5688 if (RD->getNumVBases() == 0)
5689 return;
5690
5691 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
5692 e = RD->bases_end(); i != e; ++i) {
5693 const CXXRecordDecl *Base =
5694 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
5695 if (i->isVirtual())
5696 continue;
5697 if (Base->getNumVBases() == 0)
5698 continue;
5699 MarkVirtualMembersReferenced(Loc, Base);
5700 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00005701}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00005702
5703/// SetIvarInitializers - This routine builds initialization ASTs for the
5704/// Objective-C implementation whose ivars need be initialized.
5705void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
5706 if (!getLangOptions().CPlusPlus)
5707 return;
5708 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
5709 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
5710 CollectIvarsToConstructOrDestruct(OID, ivars);
5711 if (ivars.empty())
5712 return;
5713 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
5714 for (unsigned i = 0; i < ivars.size(); i++) {
5715 FieldDecl *Field = ivars[i];
5716 CXXBaseOrMemberInitializer *Member;
5717 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
5718 InitializationKind InitKind =
5719 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
5720
5721 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
5722 Sema::OwningExprResult MemberInit =
5723 InitSeq.Perform(*this, InitEntity, InitKind,
5724 Sema::MultiExprArg(*this, 0, 0));
5725 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
5726 // Note, MemberInit could actually come back empty if no initialization
5727 // is required (e.g., because it would call a trivial default constructor)
5728 if (!MemberInit.get() || MemberInit.isInvalid())
5729 continue;
5730
5731 Member =
5732 new (Context) CXXBaseOrMemberInitializer(Context,
5733 Field, SourceLocation(),
5734 SourceLocation(),
5735 MemberInit.takeAs<Expr>(),
5736 SourceLocation());
5737 AllToInit.push_back(Member);
5738 }
5739 ObjCImplementation->setIvarInitializers(Context,
5740 AllToInit.data(), AllToInit.size());
5741 }
5742}