blob: 6b87463a6fac1c8cd744f409ef52f1c528f389ac [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000019#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000025#include "clang/AST/TypeOrdering.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000026#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000031#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000032#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000033
34using namespace clang;
35
Chris Lattner58258242008-04-10 02:22:51 +000036//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
Chris Lattnerb0d38442008-04-12 23:52:44 +000040namespace {
41 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
42 /// the default argument of a parameter to determine whether it
43 /// contains any ill-formed subexpressions. For example, this will
44 /// diagnose the use of local variables or parameters within the
45 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000046 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 Expr *DefaultArg;
49 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000050
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 public:
Mike Stump11289f42009-09-09 15:08:12 +000052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 bool VisitExpr(Expr *Node);
56 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000057 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 };
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 /// VisitExpr - Visit all of the children of this expression.
61 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
62 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000063 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000064 E = Node->child_end(); I != E; ++I)
65 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000067 }
68
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 /// VisitDeclRefExpr - Visit a reference to a declaration, to
70 /// determine whether this declaration can be used in the default
71 /// argument expression.
72 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
75 // C++ [dcl.fct.default]p9
76 // Default arguments are evaluated each time the function is
77 // called. The order of evaluation of function arguments is
78 // unspecified. Consequently, parameters of a function shall not
79 // be used in default argument expressions, even if they are not
80 // evaluated. Parameters of a function declared before a default
81 // argument expression are in scope and can hide namespace and
82 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000083 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000084 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000085 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000087 // C++ [dcl.fct.default]p7
88 // Local variables shall not be used in default argument
89 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000090 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000091 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000093 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000094 }
Chris Lattner58258242008-04-10 02:22:51 +000095
Douglas Gregor8e12c382008-11-04 13:41:56 +000096 return false;
97 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000098
Douglas Gregor97a9c812008-11-04 14:32:21 +000099 /// VisitCXXThisExpr - Visit a C++ "this" expression.
100 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
101 // C++ [dcl.fct.default]p8:
102 // The keyword this shall not be used in a default argument of a
103 // member function.
104 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_this)
106 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000107 }
Chris Lattner58258242008-04-10 02:22:51 +0000108}
109
Anders Carlssonc80a1272009-08-25 02:29:20 +0000110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000112 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssonc80a1272009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Anders Carlssonc80a1272009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Douglas Gregor85dabae2009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
131 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
132 MultiExprArg(*this, (void**)&Arg, 1));
133 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000134 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136
Anders Carlsson6e997b22009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000143
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000144 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000145}
146
Chris Lattner58258242008-04-10 02:22:51 +0000147/// ActOnParamDefaultArgument - Check whether the default argument
148/// provided for a function parameter is well-formed. If so, attach it
149/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000150void
Mike Stump11289f42009-09-09 15:08:12 +0000151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000152 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000153 if (!param || !defarg.get())
154 return;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner83f095c2009-03-28 19:18:32 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000160
161 // Default arguments are only permitted in C++
162 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000163 Diag(EqualLoc, diag::err_param_default_argument)
164 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000165 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000166 return;
167 }
168
Anders Carlssonf1c26952009-08-25 01:02:06 +0000169 // Check that the default argument is well-formed
170 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
171 if (DefaultArgChecker.Visit(DefaultArg.get())) {
172 Param->setInvalidDecl();
173 return;
174 }
Mike Stump11289f42009-09-09 15:08:12 +0000175
Anders Carlssonc80a1272009-08-25 02:29:20 +0000176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000177}
178
Douglas Gregor58354032008-12-24 00:01:03 +0000179/// ActOnParamUnparsedDefaultArgument - We've seen a default
180/// argument for a function parameter, but we can't parse it yet
181/// because we're inside a class definition. Note that this default
182/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000184 SourceLocation EqualLoc,
185 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000186 if (!param)
187 return;
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner83f095c2009-03-28 19:18:32 +0000189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000190 if (Param)
191 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000192
Anders Carlsson84613c42009-06-12 16:51:40 +0000193 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000194}
195
Douglas Gregor4d87df52008-12-16 21:30:33 +0000196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000199 if (!param)
200 return;
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000205
Anders Carlsson84613c42009-06-12 16:51:40 +0000206 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000207}
208
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000209/// CheckExtraCXXDefaultArguments - Check for any extra default
210/// arguments in the declarator, which is not a function declaration
211/// or definition and therefore is not permitted to have default
212/// arguments. This routine should be invoked for every declarator
213/// that is not a function declaration or definition.
214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
215 // C++ [dcl.fct.default]p3
216 // A default argument expression shall be specified only in the
217 // parameter-declaration-clause of a function declaration or in a
218 // template-parameter (14.1). It shall not be specified for a
219 // parameter pack. If it is specified in a
220 // parameter-declaration-clause, it shall not occur within a
221 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000223 DeclaratorChunk &chunk = D.getTypeObject(i);
224 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000225 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
226 ParmVarDecl *Param =
227 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000228 if (Param->hasUnparsedDefaultArg()) {
229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
232 delete Toks;
233 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000234 } else if (Param->getDefaultArg()) {
235 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
236 << Param->getDefaultArg()->getSourceRange();
237 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000238 }
239 }
240 }
241 }
242}
243
Chris Lattner199abbc2008-04-08 05:04:30 +0000244// MergeCXXFunctionDecl - Merge two declarations of the same C++
245// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000246// type. Subroutine of MergeFunctionDecl. Returns true if there was an
247// error, false otherwise.
248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
249 bool Invalid = false;
250
Chris Lattner199abbc2008-04-08 05:04:30 +0000251 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000252 // For non-template functions, default arguments can be added in
253 // later declarations of a function in the same
254 // scope. Declarations in different scopes have completely
255 // distinct sets of default arguments. That is, declarations in
256 // inner scopes do not acquire default arguments from
257 // declarations in outer scopes, and vice versa. In a given
258 // function declaration, all parameters subsequent to a
259 // parameter with a default argument shall have default
260 // arguments supplied in this or previous declarations. A
261 // default argument shall not be redefined by a later
262 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000263 //
264 // C++ [dcl.fct.default]p6:
265 // Except for member functions of class templates, the default arguments
266 // in a member function definition that appears outside of the class
267 // definition are added to the set of default arguments provided by the
268 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
270 ParmVarDecl *OldParam = Old->getParamDecl(p);
271 ParmVarDecl *NewParam = New->getParamDecl(p);
272
Douglas Gregorc732aba2009-09-11 18:44:32 +0000273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000274 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
275 // hint here. Alternatively, we could walk the type-source information
276 // for NewParam to find the last source location in the type... but it
277 // isn't worth the effort right now. This is the kind of test case that
278 // is hard to get right:
279
280 // int f(int);
281 // void g(int (*fp)(int) = f);
282 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000285 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000286
287 // Look for the function declaration where the default argument was
288 // actually written, which may be a declaration prior to Old.
289 for (FunctionDecl *Older = Old->getPreviousDeclaration();
290 Older; Older = Older->getPreviousDeclaration()) {
291 if (!Older->getParamDecl(p)->hasDefaultArg())
292 break;
293
294 OldParam = Older->getParamDecl(p);
295 }
296
297 Diag(OldParam->getLocation(), diag::note_previous_definition)
298 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000299 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000300 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000301 // Merge the old default argument into the new parameter.
302 // It's important to use getInit() here; getDefaultArg()
303 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000304 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000305 if (OldParam->hasUninstantiatedDefaultArg())
306 NewParam->setUninstantiatedDefaultArg(
307 OldParam->getUninstantiatedDefaultArg());
308 else
John McCalle61b02b2010-05-04 01:53:42 +0000309 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000310 } else if (NewParam->hasDefaultArg()) {
311 if (New->getDescribedFunctionTemplate()) {
312 // Paragraph 4, quoted above, only applies to non-template functions.
313 Diag(NewParam->getLocation(),
314 diag::err_param_default_argument_template_redecl)
315 << NewParam->getDefaultArgRange();
316 Diag(Old->getLocation(), diag::note_template_prev_declaration)
317 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000318 } else if (New->getTemplateSpecializationKind()
319 != TSK_ImplicitInstantiation &&
320 New->getTemplateSpecializationKind() != TSK_Undeclared) {
321 // C++ [temp.expr.spec]p21:
322 // Default function arguments shall not be specified in a declaration
323 // or a definition for one of the following explicit specializations:
324 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000325 // - the explicit specialization of a member function template;
326 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000327 // template where the class template specialization to which the
328 // member function specialization belongs is implicitly
329 // instantiated.
330 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
331 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
332 << New->getDeclName()
333 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000334 } else if (New->getDeclContext()->isDependentContext()) {
335 // C++ [dcl.fct.default]p6 (DR217):
336 // Default arguments for a member function of a class template shall
337 // be specified on the initial declaration of the member function
338 // within the class template.
339 //
340 // Reading the tea leaves a bit in DR217 and its reference to DR205
341 // leads me to the conclusion that one cannot add default function
342 // arguments for an out-of-line definition of a member function of a
343 // dependent type.
344 int WhichKind = 2;
345 if (CXXRecordDecl *Record
346 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
347 if (Record->getDescribedClassTemplate())
348 WhichKind = 0;
349 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
350 WhichKind = 1;
351 else
352 WhichKind = 2;
353 }
354
355 Diag(NewParam->getLocation(),
356 diag::err_param_default_argument_member_template_redecl)
357 << WhichKind
358 << NewParam->getDefaultArgRange();
359 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000360 }
361 }
362
Douglas Gregorf40863c2010-02-12 07:32:17 +0000363 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000364 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000365
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000366 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000367}
368
369/// CheckCXXDefaultArguments - Verify that the default arguments for a
370/// function declaration are well-formed according to C++
371/// [dcl.fct.default].
372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
373 unsigned NumParams = FD->getNumParams();
374 unsigned p;
375
376 // Find first parameter with a default argument
377 for (p = 0; p < NumParams; ++p) {
378 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000379 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000380 break;
381 }
382
383 // C++ [dcl.fct.default]p4:
384 // In a given function declaration, all parameters
385 // subsequent to a parameter with a default argument shall
386 // have default arguments supplied in this or previous
387 // declarations. A default argument shall not be redefined
388 // by a later declaration (not even to the same value).
389 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000390 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000391 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000392 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000393 if (Param->isInvalidDecl())
394 /* We already complained about this parameter. */;
395 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000397 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000398 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 else
Mike Stump11289f42009-09-09 15:08:12 +0000400 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000401 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner199abbc2008-04-08 05:04:30 +0000403 LastMissingDefaultArg = p;
404 }
405 }
406
407 if (LastMissingDefaultArg > 0) {
408 // Some default arguments were missing. Clear out all of the
409 // default arguments up to (and including) the last missing
410 // default argument, so that we leave the function parameters
411 // in a semantically valid state.
412 for (p = 0; p <= LastMissingDefaultArg; ++p) {
413 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000414 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000415 if (!Param->hasUnparsedDefaultArg())
416 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000417 Param->setDefaultArg(0);
418 }
419 }
420 }
421}
Douglas Gregor556877c2008-04-13 21:30:24 +0000422
Douglas Gregor61956c42008-10-31 09:07:45 +0000423/// isCurrentClassName - Determine whether the identifier II is the
424/// name of the class type currently being defined. In the case of
425/// nested classes, this will only return true if II is the name of
426/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000427bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
428 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000429 assert(getLangOptions().CPlusPlus && "No class names in C!");
430
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000431 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000432 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000433 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
435 } else
436 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
437
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000438 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000439 return &II == CurDecl->getIdentifier();
440 else
441 return false;
442}
443
Mike Stump11289f42009-09-09 15:08:12 +0000444/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000445///
446/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
447/// and returns NULL otherwise.
448CXXBaseSpecifier *
449Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
450 SourceRange SpecifierRange,
451 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000452 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000453 SourceLocation BaseLoc) {
454 // C++ [class.union]p1:
455 // A union shall not have base classes.
456 if (Class->isUnion()) {
457 Diag(Class->getLocation(), diag::err_base_clause_on_union)
458 << SpecifierRange;
459 return 0;
460 }
461
462 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000463 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000464 Class->getTagKind() == RecordDecl::TK_class,
465 Access, BaseType);
466
467 // Base specifiers must be record types.
468 if (!BaseType->isRecordType()) {
469 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.union]p1:
474 // A union shall not be used as a base class.
475 if (BaseType->isUnionType()) {
476 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
477 return 0;
478 }
479
480 // C++ [class.derived]p2:
481 // The class-name in a base-specifier shall not be an incompletely
482 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000483 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000484 PDiag(diag::err_incomplete_base_class)
485 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 return 0;
487
Eli Friedmanc96d4962009-08-15 21:55:26 +0000488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000491 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000495
Alexis Hunt96d5c762009-11-21 08:43:09 +0000496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
497 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000501 return 0;
502 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000503
Eli Friedman89c038e2009-12-05 23:03:49 +0000504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000505
506 // Create the base specifier.
507 // FIXME: Allocate via ASTContext?
508 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
509 Class->getTagKind() == RecordDecl::TK_class,
510 Access, BaseType);
511}
512
513void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
514 const CXXRecordDecl *BaseClass,
515 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000516 // A class with a non-empty base class is not empty.
517 // FIXME: Standard ref?
518 if (!BaseClass->isEmpty())
519 Class->setEmpty(false);
520
521 // C++ [class.virtual]p1:
522 // A class that [...] inherits a virtual function is called a polymorphic
523 // class.
524 if (BaseClass->isPolymorphic())
525 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000526
Douglas Gregor463421d2009-03-03 04:44:36 +0000527 // C++ [dcl.init.aggr]p1:
528 // An aggregate is [...] a class with [...] no base classes [...].
529 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000530
531 // C++ [class]p4:
532 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000533 Class->setPOD(false);
534
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000535 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000536 // C++ [class.ctor]p5:
537 // A constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000539
540 // C++ [class.copy]p6:
541 // A copy constructor is trivial if its class has no virtual base classes.
542 Class->setHasTrivialCopyConstructor(false);
543
544 // C++ [class.copy]p11:
545 // A copy assignment operator is trivial if its class has no virtual
546 // base classes.
547 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000548
549 // C++0x [meta.unary.prop] is_empty:
550 // T is a class type, but not a union type, with ... no virtual base
551 // classes
552 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000553 } else {
554 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000555 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000556 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000557 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000558 Class->setHasTrivialConstructor(false);
559
560 // C++ [class.copy]p6:
561 // A copy constructor is trivial if all the direct base classes of its
562 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000563 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000564 Class->setHasTrivialCopyConstructor(false);
565
566 // C++ [class.copy]p11:
567 // A copy assignment operator is trivial if all the direct base classes
568 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000569 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000570 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000571 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000572
573 // C++ [class.ctor]p3:
574 // A destructor is trivial if all the direct base classes of its class
575 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000576 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000577 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000578}
579
Douglas Gregor556877c2008-04-13 21:30:24 +0000580/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
581/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000582/// example:
583/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000584/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000585Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000586Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000587 bool Virtual, AccessSpecifier Access,
588 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000589 if (!classdecl)
590 return true;
591
Douglas Gregorc40290e2009-03-09 23:48:35 +0000592 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000593 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
594 if (!Class)
595 return true;
596
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000597 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000598 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
599 Virtual, Access,
600 BaseType, BaseLoc))
601 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000604}
Douglas Gregor556877c2008-04-13 21:30:24 +0000605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606/// \brief Performs the actual work of attaching the given base class
607/// specifiers to a C++ class.
608bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
609 unsigned NumBases) {
610 if (NumBases == 0)
611 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000612
613 // Used to keep track of which base types we have already seen, so
614 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615 // that the key is always the unqualified canonical type of the base
616 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000617 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
618
619 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000620 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000622 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000623 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000625 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000626
Douglas Gregor29a92472008-10-22 17:49:05 +0000627 if (KnownBaseTypes[NewBaseType]) {
628 // C++ [class.mi]p3:
629 // A class shall not be specified as a direct base class of a
630 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000632 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000633 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000634 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000635
636 // Delete the duplicate base class specifier; we're going to
637 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000638 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000639
640 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000641 } else {
642 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000643 KnownBaseTypes[NewBaseType] = Bases[idx];
644 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000645 }
646 }
647
648 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000649 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000650
651 // Delete the remaining (good) base class specifiers, since their
652 // data has been copied into the CXXRecordDecl.
653 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000654 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000655
656 return Invalid;
657}
658
659/// ActOnBaseSpecifiers - Attach the given base specifiers to the
660/// class, after checking whether there are any duplicate base
661/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000662void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000663 unsigned NumBases) {
664 if (!ClassDecl || !Bases || !NumBases)
665 return;
666
667 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000668 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000669 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000670}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000671
John McCalle78aac42010-03-10 03:28:59 +0000672static CXXRecordDecl *GetClassForType(QualType T) {
673 if (const RecordType *RT = T->getAs<RecordType>())
674 return cast<CXXRecordDecl>(RT->getDecl());
675 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
676 return ICT->getDecl();
677 else
678 return 0;
679}
680
Douglas Gregor36d1b142009-10-06 17:59:45 +0000681/// \brief Determine whether the type \p Derived is a C++ class that is
682/// derived from the type \p Base.
683bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
684 if (!getLangOptions().CPlusPlus)
685 return false;
John McCalle78aac42010-03-10 03:28:59 +0000686
687 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
688 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000689 return false;
690
John McCalle78aac42010-03-10 03:28:59 +0000691 CXXRecordDecl *BaseRD = GetClassForType(Base);
692 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000693 return false;
694
John McCall67da35c2010-02-04 22:26:26 +0000695 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
696 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000697}
698
699/// \brief Determine whether the type \p Derived is a C++ class that is
700/// derived from the type \p Base.
701bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
702 if (!getLangOptions().CPlusPlus)
703 return false;
704
John McCalle78aac42010-03-10 03:28:59 +0000705 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
706 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000707 return false;
708
John McCalle78aac42010-03-10 03:28:59 +0000709 CXXRecordDecl *BaseRD = GetClassForType(Base);
710 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000711 return false;
712
Douglas Gregor36d1b142009-10-06 17:59:45 +0000713 return DerivedRD->isDerivedFrom(BaseRD, Paths);
714}
715
Anders Carlssona70cff62010-04-24 19:06:50 +0000716void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
717 CXXBaseSpecifierArray &BasePathArray) {
718 assert(BasePathArray.empty() && "Base path array must be empty!");
719 assert(Paths.isRecordingPaths() && "Must record paths!");
720
721 const CXXBasePath &Path = Paths.front();
722
723 // We first go backward and check if we have a virtual base.
724 // FIXME: It would be better if CXXBasePath had the base specifier for
725 // the nearest virtual base.
726 unsigned Start = 0;
727 for (unsigned I = Path.size(); I != 0; --I) {
728 if (Path[I - 1].Base->isVirtual()) {
729 Start = I - 1;
730 break;
731 }
732 }
733
734 // Now add all bases.
735 for (unsigned I = Start, E = Path.size(); I != E; ++I)
736 BasePathArray.push_back(Path[I].Base);
737}
738
Douglas Gregor36d1b142009-10-06 17:59:45 +0000739/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
740/// conversion (where Derived and Base are class types) is
741/// well-formed, meaning that the conversion is unambiguous (and
742/// that all of the base classes are accessible). Returns true
743/// and emits a diagnostic if the code is ill-formed, returns false
744/// otherwise. Loc is the location where this routine should point to
745/// if there is an error, and Range is the source range to highlight
746/// if there is an error.
747bool
748Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000749 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000750 unsigned AmbigiousBaseConvID,
751 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000752 DeclarationName Name,
753 CXXBaseSpecifierArray *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000754 // First, determine whether the path from Derived to Base is
755 // ambiguous. This is slightly more expensive than checking whether
756 // the Derived to Base conversion exists, because here we need to
757 // explore multiple paths to determine if there is an ambiguity.
758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
759 /*DetectVirtual=*/false);
760 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
761 assert(DerivationOkay &&
762 "Can only be used with a derived-to-base conversion");
763 (void)DerivationOkay;
764
765 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000766 if (InaccessibleBaseID) {
767 // Check that the base class can be accessed.
768 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
769 InaccessibleBaseID)) {
770 case AR_inaccessible:
771 return true;
772 case AR_accessible:
773 case AR_dependent:
774 case AR_delayed:
775 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000776 }
John McCall5b0829a2010-02-10 09:31:12 +0000777 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000778
779 // Build a base path if necessary.
780 if (BasePath)
781 BuildBasePathArray(Paths, *BasePath);
782 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000783 }
784
785 // We know that the derived-to-base conversion is ambiguous, and
786 // we're going to produce a diagnostic. Perform the derived-to-base
787 // search just one more time to compute all of the possible paths so
788 // that we can print them out. This is more expensive than any of
789 // the previous derived-to-base checks we've done, but at this point
790 // performance isn't as much of an issue.
791 Paths.clear();
792 Paths.setRecordingPaths(true);
793 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
794 assert(StillOkay && "Can only be used with a derived-to-base conversion");
795 (void)StillOkay;
796
797 // Build up a textual representation of the ambiguous paths, e.g.,
798 // D -> B -> A, that will be used to illustrate the ambiguous
799 // conversions in the diagnostic. We only print one of the paths
800 // to each base class subobject.
801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
802
803 Diag(Loc, AmbigiousBaseConvID)
804 << Derived << Base << PathDisplayStr << Range << Name;
805 return true;
806}
807
808bool
809Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000810 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000811 CXXBaseSpecifierArray *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000812 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000813 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000814 IgnoreAccess ? 0
815 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000816 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000817 Loc, Range, DeclarationName(),
818 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000819}
820
821
822/// @brief Builds a string representing ambiguous paths from a
823/// specific derived class to different subobjects of the same base
824/// class.
825///
826/// This function builds a string that can be used in error messages
827/// to show the different paths that one can take through the
828/// inheritance hierarchy to go from the derived class to different
829/// subobjects of a base class. The result looks something like this:
830/// @code
831/// struct D -> struct B -> struct A
832/// struct D -> struct C -> struct A
833/// @endcode
834std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
835 std::string PathDisplayStr;
836 std::set<unsigned> DisplayedPaths;
837 for (CXXBasePaths::paths_iterator Path = Paths.begin();
838 Path != Paths.end(); ++Path) {
839 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
840 // We haven't displayed a path to this particular base
841 // class subobject yet.
842 PathDisplayStr += "\n ";
843 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
844 for (CXXBasePath::const_iterator Element = Path->begin();
845 Element != Path->end(); ++Element)
846 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
847 }
848 }
849
850 return PathDisplayStr;
851}
852
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853//===----------------------------------------------------------------------===//
854// C++ class member Handling
855//===----------------------------------------------------------------------===//
856
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000857/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
858/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
859/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000860/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000861Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000862Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000863 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000864 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
865 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000866 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000867 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000868 Expr *BitWidth = static_cast<Expr*>(BW);
869 Expr *Init = static_cast<Expr*>(InitExpr);
870 SourceLocation Loc = D.getIdentifierLoc();
871
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000872 bool isFunc = D.isFunctionDeclarator();
873
John McCall07e91c02009-08-06 02:15:43 +0000874 assert(!DS.isFriendSpecified());
875
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876 // C++ 9.2p6: A member shall not be declared to have automatic storage
877 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000878 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
879 // data members and cannot be applied to names declared const or static,
880 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000881 switch (DS.getStorageClassSpec()) {
882 case DeclSpec::SCS_unspecified:
883 case DeclSpec::SCS_typedef:
884 case DeclSpec::SCS_static:
885 // FALL THROUGH.
886 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000887 case DeclSpec::SCS_mutable:
888 if (isFunc) {
889 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000890 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000891 else
Chris Lattner3b054132008-11-19 05:08:23 +0000892 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000893
Sebastian Redl8071edb2008-11-17 23:24:37 +0000894 // FIXME: It would be nicer if the keyword was ignored only for this
895 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000896 D.getMutableDeclSpec().ClearStorageClassSpecs();
897 } else {
898 QualType T = GetTypeForDeclarator(D, S);
899 diag::kind err = static_cast<diag::kind>(0);
900 if (T->isReferenceType())
901 err = diag::err_mutable_reference;
902 else if (T.isConstQualified())
903 err = diag::err_mutable_const;
904 if (err != 0) {
905 if (DS.getStorageClassSpecLoc().isValid())
906 Diag(DS.getStorageClassSpecLoc(), err);
907 else
908 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000909 // FIXME: It would be nicer if the keyword was ignored only for this
910 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000911 D.getMutableDeclSpec().ClearStorageClassSpecs();
912 }
913 }
914 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915 default:
916 if (DS.getStorageClassSpecLoc().isValid())
917 Diag(DS.getStorageClassSpecLoc(),
918 diag::err_storageclass_invalid_for_member);
919 else
920 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
921 D.getMutableDeclSpec().ClearStorageClassSpecs();
922 }
923
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000924 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000925 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000926 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000927 // Check also for this case:
928 //
929 // typedef int f();
930 // f a;
931 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000932 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000933 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000934 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000936 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
937 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000938 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000939
940 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000941 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000942 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000943 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
944 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000945 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000946 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000947 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000948 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000949 if (!Member) {
950 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000951 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000952 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000953
954 // Non-instance-fields can't have a bitfield.
955 if (BitWidth) {
956 if (Member->isInvalidDecl()) {
957 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000958 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000959 // C++ 9.6p3: A bit-field shall not be a static member.
960 // "static member 'A' cannot be a bit-field"
961 Diag(Loc, diag::err_static_not_bitfield)
962 << Name << BitWidth->getSourceRange();
963 } else if (isa<TypedefDecl>(Member)) {
964 // "typedef member 'x' cannot be a bit-field"
965 Diag(Loc, diag::err_typedef_not_bitfield)
966 << Name << BitWidth->getSourceRange();
967 } else {
968 // A function typedef ("typedef int f(); f a;").
969 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
970 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000971 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000972 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000973 }
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattnerd26760a2009-03-05 23:01:03 +0000975 DeleteExpr(BitWidth);
976 BitWidth = 0;
977 Member->setInvalidDecl();
978 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000979
980 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000981
Douglas Gregor3447e762009-08-20 22:52:58 +0000982 // If we have declared a member function template, set the access of the
983 // templated declaration as well.
984 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
985 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000986 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000987
Douglas Gregor92751d42008-11-17 22:58:34 +0000988 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000989
Douglas Gregor0c880302009-03-11 23:00:04 +0000990 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000991 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000992 if (Deleted) // FIXME: Source location is not very good.
993 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000994
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000995 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000996 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000997 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000999 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001000}
1001
Douglas Gregor15e77a22009-12-31 09:10:24 +00001002/// \brief Find the direct and/or virtual base specifiers that
1003/// correspond to the given base type, for use in base initialization
1004/// within a constructor.
1005static bool FindBaseInitializer(Sema &SemaRef,
1006 CXXRecordDecl *ClassDecl,
1007 QualType BaseType,
1008 const CXXBaseSpecifier *&DirectBaseSpec,
1009 const CXXBaseSpecifier *&VirtualBaseSpec) {
1010 // First, check for a direct base class.
1011 DirectBaseSpec = 0;
1012 for (CXXRecordDecl::base_class_const_iterator Base
1013 = ClassDecl->bases_begin();
1014 Base != ClassDecl->bases_end(); ++Base) {
1015 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1016 // We found a direct base of this type. That's what we're
1017 // initializing.
1018 DirectBaseSpec = &*Base;
1019 break;
1020 }
1021 }
1022
1023 // Check for a virtual base class.
1024 // FIXME: We might be able to short-circuit this if we know in advance that
1025 // there are no virtual bases.
1026 VirtualBaseSpec = 0;
1027 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1028 // We haven't found a base yet; search the class hierarchy for a
1029 // virtual base class.
1030 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1031 /*DetectVirtual=*/false);
1032 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1033 BaseType, Paths)) {
1034 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1035 Path != Paths.end(); ++Path) {
1036 if (Path->back().Base->isVirtual()) {
1037 VirtualBaseSpec = Path->back().Base;
1038 break;
1039 }
1040 }
1041 }
1042 }
1043
1044 return DirectBaseSpec || VirtualBaseSpec;
1045}
1046
Douglas Gregore8381c02008-11-05 04:29:56 +00001047/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001048Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001049Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001050 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001051 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001052 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001053 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001054 SourceLocation IdLoc,
1055 SourceLocation LParenLoc,
1056 ExprTy **Args, unsigned NumArgs,
1057 SourceLocation *CommaLocs,
1058 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001059 if (!ConstructorD)
1060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001061
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001062 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001063
1064 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001065 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001066 if (!Constructor) {
1067 // The user wrote a constructor initializer on a function that is
1068 // not a C++ constructor. Ignore the error for now, because we may
1069 // have more member initializers coming; we'll diagnose it just
1070 // once in ActOnMemInitializers.
1071 return true;
1072 }
1073
1074 CXXRecordDecl *ClassDecl = Constructor->getParent();
1075
1076 // C++ [class.base.init]p2:
1077 // Names in a mem-initializer-id are looked up in the scope of the
1078 // constructor’s class and, if not found in that scope, are looked
1079 // up in the scope containing the constructor’s
1080 // definition. [Note: if the constructor’s class contains a member
1081 // with the same name as a direct or virtual base class of the
1082 // class, a mem-initializer-id naming the member or base class and
1083 // composed of a single identifier refers to the class member. A
1084 // mem-initializer-id for the hidden base class may be specified
1085 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001086 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001087 // Look for a member, first.
1088 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001089 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001090 = ClassDecl->lookup(MemberOrBase);
1091 if (Result.first != Result.second)
1092 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001093
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001094 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001095
Eli Friedman8e1433b2009-07-29 19:44:27 +00001096 if (Member)
1097 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001098 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001099 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001100 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001101 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001102 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001103
1104 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001105 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001106 } else {
1107 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1108 LookupParsedName(R, S, &SS);
1109
1110 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1111 if (!TyD) {
1112 if (R.isAmbiguous()) return true;
1113
John McCallda6841b2010-04-09 19:01:14 +00001114 // We don't want access-control diagnostics here.
1115 R.suppressDiagnostics();
1116
Douglas Gregora3b624a2010-01-19 06:46:48 +00001117 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1118 bool NotUnknownSpecialization = false;
1119 DeclContext *DC = computeDeclContext(SS, false);
1120 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1121 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1122
1123 if (!NotUnknownSpecialization) {
1124 // When the scope specifier can refer to a member of an unknown
1125 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001126 BaseType = CheckTypenameType(ETK_None,
1127 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora3b624a2010-01-19 06:46:48 +00001128 *MemberOrBase, SS.getRange());
Douglas Gregor281c4862010-03-07 23:26:22 +00001129 if (BaseType.isNull())
1130 return true;
1131
Douglas Gregora3b624a2010-01-19 06:46:48 +00001132 R.clear();
1133 }
1134 }
1135
Douglas Gregor15e77a22009-12-31 09:10:24 +00001136 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001137 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001138 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1139 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001140 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1141 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1142 // We have found a non-static data member with a similar
1143 // name to what was typed; complain and initialize that
1144 // member.
1145 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1146 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001147 << FixItHint::CreateReplacement(R.getNameLoc(),
1148 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001149 Diag(Member->getLocation(), diag::note_previous_decl)
1150 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001151
1152 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1153 LParenLoc, RParenLoc);
1154 }
1155 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1156 const CXXBaseSpecifier *DirectBaseSpec;
1157 const CXXBaseSpecifier *VirtualBaseSpec;
1158 if (FindBaseInitializer(*this, ClassDecl,
1159 Context.getTypeDeclType(Type),
1160 DirectBaseSpec, VirtualBaseSpec)) {
1161 // We have found a direct or virtual base class with a
1162 // similar name to what was typed; complain and initialize
1163 // that base class.
1164 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1165 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001166 << FixItHint::CreateReplacement(R.getNameLoc(),
1167 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001168
1169 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1170 : VirtualBaseSpec;
1171 Diag(BaseSpec->getSourceRange().getBegin(),
1172 diag::note_base_class_specified_here)
1173 << BaseSpec->getType()
1174 << BaseSpec->getSourceRange();
1175
Douglas Gregor15e77a22009-12-31 09:10:24 +00001176 TyD = Type;
1177 }
1178 }
1179 }
1180
Douglas Gregora3b624a2010-01-19 06:46:48 +00001181 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001182 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1183 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1184 return true;
1185 }
John McCallb5a0d312009-12-21 10:41:20 +00001186 }
1187
Douglas Gregora3b624a2010-01-19 06:46:48 +00001188 if (BaseType.isNull()) {
1189 BaseType = Context.getTypeDeclType(TyD);
1190 if (SS.isSet()) {
1191 NestedNameSpecifier *Qualifier =
1192 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001193
Douglas Gregora3b624a2010-01-19 06:46:48 +00001194 // FIXME: preserve source range information
1195 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1196 }
John McCallb5a0d312009-12-21 10:41:20 +00001197 }
1198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
John McCallbcd03502009-12-07 02:54:59 +00001200 if (!TInfo)
1201 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001202
John McCallbcd03502009-12-07 02:54:59 +00001203 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001204 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001205}
1206
John McCalle22a04a2009-11-04 23:02:40 +00001207/// Checks an initializer expression for use of uninitialized fields, such as
1208/// containing the field that is being initialized. Returns true if there is an
1209/// uninitialized field was used an updates the SourceLocation parameter; false
1210/// otherwise.
1211static bool InitExprContainsUninitializedFields(const Stmt* S,
1212 const FieldDecl* LhsField,
1213 SourceLocation* L) {
1214 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1215 if (ME) {
1216 const NamedDecl* RhsField = ME->getMemberDecl();
1217 if (RhsField == LhsField) {
1218 // Initializing a field with itself. Throw a warning.
1219 // But wait; there are exceptions!
1220 // Exception #1: The field may not belong to this record.
1221 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1222 const Expr* base = ME->getBase();
1223 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1224 // Even though the field matches, it does not belong to this record.
1225 return false;
1226 }
1227 // None of the exceptions triggered; return true to indicate an
1228 // uninitialized field was used.
1229 *L = ME->getMemberLoc();
1230 return true;
1231 }
1232 }
1233 bool found = false;
1234 for (Stmt::const_child_iterator it = S->child_begin();
1235 it != S->child_end() && found == false;
1236 ++it) {
1237 if (isa<CallExpr>(S)) {
1238 // Do not descend into function calls or constructors, as the use
1239 // of an uninitialized field may be valid. One would have to inspect
1240 // the contents of the function/ctor to determine if it is safe or not.
1241 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1242 // may be safe, depending on what the function/ctor does.
1243 continue;
1244 }
1245 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1246 }
1247 return found;
1248}
1249
Eli Friedman8e1433b2009-07-29 19:44:27 +00001250Sema::MemInitResult
1251Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1252 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001253 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001254 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001255 // Diagnose value-uses of fields to initialize themselves, e.g.
1256 // foo(foo)
1257 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001258 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001259 for (unsigned i = 0; i < NumArgs; ++i) {
1260 SourceLocation L;
1261 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1262 // FIXME: Return true in the case when other fields are used before being
1263 // uninitialized. For example, let this field be the i'th field. When
1264 // initializing the i'th field, throw a warning if any of the >= i'th
1265 // fields are used, as they are not yet initialized.
1266 // Right now we are only handling the case where the i'th field uses
1267 // itself in its initializer.
1268 Diag(L, diag::warn_field_is_uninit);
1269 }
1270 }
1271
Eli Friedman8e1433b2009-07-29 19:44:27 +00001272 bool HasDependentArg = false;
1273 for (unsigned i = 0; i < NumArgs; i++)
1274 HasDependentArg |= Args[i]->isTypeDependent();
1275
Eli Friedman8e1433b2009-07-29 19:44:27 +00001276 QualType FieldType = Member->getType();
1277 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1278 FieldType = Array->getElementType();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001279 if (FieldType->isDependentType() || HasDependentArg) {
1280 // Can't check initialization for a member of dependent type or when
1281 // any of the arguments are type-dependent expressions.
1282 OwningExprResult Init
1283 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1284 RParenLoc));
1285
1286 // Erase any temporaries within this evaluation context; we're not
1287 // going to track them in the AST, since we'll be rebuilding the
1288 // ASTs during template instantiation.
1289 ExprTemporaries.erase(
1290 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1291 ExprTemporaries.end());
1292
1293 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1294 LParenLoc,
1295 Init.takeAs<Expr>(),
1296 RParenLoc);
1297
Douglas Gregore8381c02008-11-05 04:29:56 +00001298 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001299
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001300 if (Member->isInvalidDecl())
1301 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001302
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001303 // Initialize the member.
1304 InitializedEntity MemberEntity =
1305 InitializedEntity::InitializeMember(Member, 0);
1306 InitializationKind Kind =
1307 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1308
1309 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1310
1311 OwningExprResult MemberInit =
1312 InitSeq.Perform(*this, MemberEntity, Kind,
1313 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1314 if (MemberInit.isInvalid())
1315 return true;
1316
1317 // C++0x [class.base.init]p7:
1318 // The initialization of each base and member constitutes a
1319 // full-expression.
1320 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1321 if (MemberInit.isInvalid())
1322 return true;
1323
1324 // If we are in a dependent context, template instantiation will
1325 // perform this type-checking again. Just save the arguments that we
1326 // received in a ParenListExpr.
1327 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1328 // of the information that we have about the member
1329 // initializer. However, deconstructing the ASTs is a dicey process,
1330 // and this approach is far more likely to get the corner cases right.
1331 if (CurContext->isDependentContext()) {
1332 // Bump the reference count of all of the arguments.
1333 for (unsigned I = 0; I != NumArgs; ++I)
1334 Args[I]->Retain();
1335
1336 OwningExprResult Init
1337 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1338 RParenLoc));
1339 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1340 LParenLoc,
1341 Init.takeAs<Expr>(),
1342 RParenLoc);
1343 }
1344
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001345 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001346 LParenLoc,
1347 MemberInit.takeAs<Expr>(),
1348 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001349}
1350
1351Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001352Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001353 Expr **Args, unsigned NumArgs,
1354 SourceLocation LParenLoc, SourceLocation RParenLoc,
1355 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001356 bool HasDependentArg = false;
1357 for (unsigned i = 0; i < NumArgs; i++)
1358 HasDependentArg |= Args[i]->isTypeDependent();
1359
John McCallbcd03502009-12-07 02:54:59 +00001360 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001361 if (BaseType->isDependentType() || HasDependentArg) {
1362 // Can't check initialization for a base of dependent type or when
1363 // any of the arguments are type-dependent expressions.
1364 OwningExprResult BaseInit
1365 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1366 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001367
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001368 // Erase any temporaries within this evaluation context; we're not
1369 // going to track them in the AST, since we'll be rebuilding the
1370 // ASTs during template instantiation.
1371 ExprTemporaries.erase(
1372 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1373 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001374
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001375 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001376 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001377 LParenLoc,
1378 BaseInit.takeAs<Expr>(),
1379 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001380 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001381
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001382 if (!BaseType->isRecordType())
1383 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1384 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1385
1386 // C++ [class.base.init]p2:
1387 // [...] Unless the mem-initializer-id names a nonstatic data
1388 // member of the constructor’s class or a direct or virtual base
1389 // of that class, the mem-initializer is ill-formed. A
1390 // mem-initializer-list can initialize a base class using any
1391 // name that denotes that base class type.
1392
1393 // Check for direct and virtual base classes.
1394 const CXXBaseSpecifier *DirectBaseSpec = 0;
1395 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1396 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1397 VirtualBaseSpec);
1398
1399 // C++ [base.class.init]p2:
1400 // If a mem-initializer-id is ambiguous because it designates both
1401 // a direct non-virtual base class and an inherited virtual base
1402 // class, the mem-initializer is ill-formed.
1403 if (DirectBaseSpec && VirtualBaseSpec)
1404 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1405 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1406 // C++ [base.class.init]p2:
1407 // Unless the mem-initializer-id names a nonstatic data membeer of the
1408 // constructor's class ot a direst or virtual base of that class, the
1409 // mem-initializer is ill-formed.
1410 if (!DirectBaseSpec && !VirtualBaseSpec)
1411 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall1e67dd62010-04-27 01:43:38 +00001412 << BaseType << Context.getTypeDeclType(ClassDecl)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001413 << BaseTInfo->getTypeLoc().getSourceRange();
1414
1415 CXXBaseSpecifier *BaseSpec
1416 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1417 if (!BaseSpec)
1418 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1419
1420 // Initialize the base.
1421 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001422 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001423 InitializationKind Kind =
1424 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1425
1426 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1427
1428 OwningExprResult BaseInit =
1429 InitSeq.Perform(*this, BaseEntity, Kind,
1430 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1431 if (BaseInit.isInvalid())
1432 return true;
1433
1434 // C++0x [class.base.init]p7:
1435 // The initialization of each base and member constitutes a
1436 // full-expression.
1437 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1438 if (BaseInit.isInvalid())
1439 return true;
1440
1441 // If we are in a dependent context, template instantiation will
1442 // perform this type-checking again. Just save the arguments that we
1443 // received in a ParenListExpr.
1444 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1445 // of the information that we have about the base
1446 // initializer. However, deconstructing the ASTs is a dicey process,
1447 // and this approach is far more likely to get the corner cases right.
1448 if (CurContext->isDependentContext()) {
1449 // Bump the reference count of all of the arguments.
1450 for (unsigned I = 0; I != NumArgs; ++I)
1451 Args[I]->Retain();
1452
1453 OwningExprResult Init
1454 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1455 RParenLoc));
1456 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001457 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001458 LParenLoc,
1459 Init.takeAs<Expr>(),
1460 RParenLoc);
1461 }
1462
1463 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001464 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001465 LParenLoc,
1466 BaseInit.takeAs<Expr>(),
1467 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001468}
1469
Anders Carlsson1b00e242010-04-23 03:10:23 +00001470/// ImplicitInitializerKind - How an implicit base or member initializer should
1471/// initialize its base or member.
1472enum ImplicitInitializerKind {
1473 IIK_Default,
1474 IIK_Copy,
1475 IIK_Move
1476};
1477
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001478static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001479BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001480 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001481 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001482 bool IsInheritedVirtualBase,
1483 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001484 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001485 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1486 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001487
Anders Carlsson1b00e242010-04-23 03:10:23 +00001488 Sema::OwningExprResult BaseInit(SemaRef);
1489
1490 switch (ImplicitInitKind) {
1491 case IIK_Default: {
1492 InitializationKind InitKind
1493 = InitializationKind::CreateDefault(Constructor->getLocation());
1494 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1495 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1496 Sema::MultiExprArg(SemaRef, 0, 0));
1497 break;
1498 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001499
Anders Carlsson1b00e242010-04-23 03:10:23 +00001500 case IIK_Copy: {
1501 ParmVarDecl *Param = Constructor->getParamDecl(0);
1502 QualType ParamType = Param->getType().getNonReferenceType();
1503
1504 Expr *CopyCtorArg =
1505 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001506 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001507
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001508 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001509 QualType ArgTy =
1510 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1511 ParamType.getQualifiers());
1512 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001513 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson36db0d92010-04-24 22:54:32 +00001514 /*isLvalue=*/true,
1515 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001516
Anders Carlsson1b00e242010-04-23 03:10:23 +00001517 InitializationKind InitKind
1518 = InitializationKind::CreateDirect(Constructor->getLocation(),
1519 SourceLocation(), SourceLocation());
1520 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1521 &CopyCtorArg, 1);
1522 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1523 Sema::MultiExprArg(SemaRef,
1524 (void**)&CopyCtorArg, 1));
1525 break;
1526 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001527
Anders Carlsson1b00e242010-04-23 03:10:23 +00001528 case IIK_Move:
1529 assert(false && "Unhandled initializer kind!");
1530 }
1531
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001532 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1533 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001534 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001535
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001536 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001537 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1538 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1539 SourceLocation()),
1540 BaseSpec->isVirtual(),
1541 SourceLocation(),
1542 BaseInit.takeAs<Expr>(),
1543 SourceLocation());
1544
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001545 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001546}
1547
Anders Carlsson3c1db572010-04-23 02:15:47 +00001548static bool
1549BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001550 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001551 FieldDecl *Field,
1552 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlsson423f5d82010-04-23 16:04:08 +00001553 if (ImplicitInitKind == IIK_Copy) {
Douglas Gregor94f9a482010-05-05 05:51:00 +00001554 SourceLocation Loc = Constructor->getLocation();
Anders Carlsson423f5d82010-04-23 16:04:08 +00001555 ParmVarDecl *Param = Constructor->getParamDecl(0);
1556 QualType ParamType = Param->getType().getNonReferenceType();
1557
1558 Expr *MemberExprBase =
1559 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001560 Loc, ParamType, 0);
1561
1562 // Build a reference to this field within the parameter.
1563 CXXScopeSpec SS;
1564 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1565 Sema::LookupMemberName);
1566 MemberLookup.addDecl(Field, AS_public);
1567 MemberLookup.resolveKind();
1568 Sema::OwningExprResult CopyCtorArg
1569 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1570 ParamType, Loc,
1571 /*IsArrow=*/false,
1572 SS,
1573 /*FirstQualifierInScope=*/0,
1574 MemberLookup,
1575 /*TemplateArgs=*/0);
1576 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001577 return true;
1578
Douglas Gregor94f9a482010-05-05 05:51:00 +00001579 // When the field we are copying is an array, create index variables for
1580 // each dimension of the array. We use these index variables to subscript
1581 // the source array, and other clients (e.g., CodeGen) will perform the
1582 // necessary iteration with these index variables.
1583 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1584 QualType BaseType = Field->getType();
1585 QualType SizeType = SemaRef.Context.getSizeType();
1586 while (const ConstantArrayType *Array
1587 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1588 // Create the iteration variable for this array index.
1589 IdentifierInfo *IterationVarName = 0;
1590 {
1591 llvm::SmallString<8> Str;
1592 llvm::raw_svector_ostream OS(Str);
1593 OS << "__i" << IndexVariables.size();
1594 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1595 }
1596 VarDecl *IterationVar
1597 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1598 IterationVarName, SizeType,
1599 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1600 VarDecl::None, VarDecl::None);
1601 IndexVariables.push_back(IterationVar);
1602
1603 // Create a reference to the iteration variable.
1604 Sema::OwningExprResult IterationVarRef
1605 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1606 assert(!IterationVarRef.isInvalid() &&
1607 "Reference to invented variable cannot fail!");
1608
1609 // Subscript the array with this iteration variable.
1610 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1611 Loc,
1612 move(IterationVarRef),
1613 Loc);
1614 if (CopyCtorArg.isInvalid())
1615 return true;
1616
1617 BaseType = Array->getElementType();
1618 }
1619
1620 // Construct the entity that we will be initializing. For an array, this
1621 // will be first element in the array, which may require several levels
1622 // of array-subscript entities.
1623 llvm::SmallVector<InitializedEntity, 4> Entities;
1624 Entities.reserve(1 + IndexVariables.size());
1625 Entities.push_back(InitializedEntity::InitializeMember(Field));
1626 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1627 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1628 0,
1629 Entities.back()));
1630
1631 // Direct-initialize to use the copy constructor.
1632 InitializationKind InitKind =
1633 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1634
1635 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1636 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1637 &CopyCtorArgE, 1);
1638
1639 Sema::OwningExprResult MemberInit
1640 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1641 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1642 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1643 if (MemberInit.isInvalid())
1644 return true;
1645
1646 CXXMemberInit
1647 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1648 MemberInit.takeAs<Expr>(), Loc,
1649 IndexVariables.data(),
1650 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001651 return false;
1652 }
1653
Anders Carlsson423f5d82010-04-23 16:04:08 +00001654 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1655
Anders Carlsson3c1db572010-04-23 02:15:47 +00001656 QualType FieldBaseElementType =
1657 SemaRef.Context.getBaseElementType(Field->getType());
1658
Anders Carlsson3c1db572010-04-23 02:15:47 +00001659 if (FieldBaseElementType->isRecordType()) {
1660 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001661 InitializationKind InitKind =
1662 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001663
1664 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1665 Sema::OwningExprResult MemberInit =
1666 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1667 Sema::MultiExprArg(SemaRef, 0, 0));
1668 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1669 if (MemberInit.isInvalid())
1670 return true;
1671
1672 CXXMemberInit =
1673 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1674 Field, SourceLocation(),
1675 SourceLocation(),
1676 MemberInit.takeAs<Expr>(),
1677 SourceLocation());
1678 return false;
1679 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001680
1681 if (FieldBaseElementType->isReferenceType()) {
1682 SemaRef.Diag(Constructor->getLocation(),
1683 diag::err_uninitialized_member_in_ctor)
1684 << (int)Constructor->isImplicit()
1685 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1686 << 0 << Field->getDeclName();
1687 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1688 return true;
1689 }
1690
1691 if (FieldBaseElementType.isConstQualified()) {
1692 SemaRef.Diag(Constructor->getLocation(),
1693 diag::err_uninitialized_member_in_ctor)
1694 << (int)Constructor->isImplicit()
1695 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1696 << 1 << Field->getDeclName();
1697 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1698 return true;
1699 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001700
1701 // Nothing to initialize.
1702 CXXMemberInit = 0;
1703 return false;
1704}
1705
Eli Friedman9cf6b592009-11-09 19:20:36 +00001706bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001707Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001708 CXXBaseOrMemberInitializer **Initializers,
1709 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001710 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001711 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001712 // Just store the initializers as written, they will be checked during
1713 // instantiation.
1714 if (NumInitializers > 0) {
1715 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1716 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1717 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1718 memcpy(baseOrMemberInitializers, Initializers,
1719 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1720 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1721 }
1722
1723 return false;
1724 }
1725
Anders Carlsson1b00e242010-04-23 03:10:23 +00001726 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1727
1728 // FIXME: Handle implicit move constructors.
1729 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1730 ImplicitInitKind = IIK_Copy;
1731
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001732 // We need to build the initializer AST according to order of construction
1733 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001734 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001735 if (!ClassDecl)
1736 return true;
1737
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001738 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1739 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001740 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001741
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001742 for (unsigned i = 0; i < NumInitializers; i++) {
1743 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001744
1745 if (Member->isBaseInitializer())
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001746 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001747 else
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001748 AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001749 }
1750
Anders Carlsson43c64af2010-04-21 19:52:01 +00001751 // Keep track of the direct virtual bases.
1752 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1753 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1754 E = ClassDecl->bases_end(); I != E; ++I) {
1755 if (I->isVirtual())
1756 DirectVBases.insert(I);
1757 }
1758
Anders Carlssondb0a9652010-04-02 06:26:44 +00001759 // Push virtual bases before others.
1760 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1761 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1762
1763 if (CXXBaseOrMemberInitializer *Value
1764 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1765 AllToInit.push_back(Value);
1766 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001767 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001768 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001769 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1770 VBase, IsInheritedVirtualBase,
1771 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001772 HadError = true;
1773 continue;
1774 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001775
Anders Carlssondb0a9652010-04-02 06:26:44 +00001776 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001777 }
1778 }
Mike Stump11289f42009-09-09 15:08:12 +00001779
Anders Carlssondb0a9652010-04-02 06:26:44 +00001780 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1781 E = ClassDecl->bases_end(); Base != E; ++Base) {
1782 // Virtuals are in the virtual base list and already constructed.
1783 if (Base->isVirtual())
1784 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001785
Anders Carlssondb0a9652010-04-02 06:26:44 +00001786 if (CXXBaseOrMemberInitializer *Value
1787 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1788 AllToInit.push_back(Value);
1789 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001790 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001791 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1792 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001793 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001794 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001795 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001796 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001797
Anders Carlssondb0a9652010-04-02 06:26:44 +00001798 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001799 }
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001802 // non-static data members.
1803 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1804 E = ClassDecl->field_end(); Field != E; ++Field) {
1805 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001806 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001807 Field->getType()->getAs<RecordType>()) {
1808 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001809 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001810 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001811 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1812 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1813 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1814 // set to the anonymous union data member used in the initializer
1815 // list.
1816 Value->setMember(*Field);
1817 Value->setAnonUnionMember(*FA);
1818 AllToInit.push_back(Value);
1819 break;
1820 }
1821 }
1822 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00001823
1824 if (ImplicitInitKind == IIK_Default)
1825 continue;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001826 }
1827 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1828 AllToInit.push_back(Value);
1829 continue;
1830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001832 if (AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001833 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001834
Anders Carlsson3c1db572010-04-23 02:15:47 +00001835 CXXBaseOrMemberInitializer *Member;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001836 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1837 *Field, Member)) {
Anders Carlsson3c1db572010-04-23 02:15:47 +00001838 HadError = true;
1839 continue;
1840 }
1841
1842 // If the member doesn't need to be initialized, it will be null.
1843 if (Member)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001844 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001845 }
Mike Stump11289f42009-09-09 15:08:12 +00001846
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001847 NumInitializers = AllToInit.size();
1848 if (NumInitializers > 0) {
1849 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1850 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1851 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCalla6309952010-03-16 21:39:52 +00001852 memcpy(baseOrMemberInitializers, AllToInit.data(),
1853 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001854 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001855
John McCalla6309952010-03-16 21:39:52 +00001856 // Constructors implicitly reference the base and member
1857 // destructors.
1858 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1859 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001860 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001861
1862 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001863}
1864
Eli Friedman952c15d2009-07-21 19:28:10 +00001865static void *GetKeyForTopLevelField(FieldDecl *Field) {
1866 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001868 if (RT->getDecl()->isAnonymousStructOrUnion())
1869 return static_cast<void *>(RT->getDecl());
1870 }
1871 return static_cast<void *>(Field);
1872}
1873
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001874static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1875 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001876}
1877
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001878static void *GetKeyForMember(ASTContext &Context,
1879 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001880 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001881 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001882 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001883
Eli Friedman952c15d2009-07-21 19:28:10 +00001884 // For fields injected into the class via declaration of an anonymous union,
1885 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001886 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001887
Anders Carlssona942dcd2010-03-30 15:39:27 +00001888 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1889 // data member of the class. Data member used in the initializer list is
1890 // in AnonUnionMember field.
1891 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1892 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001893
John McCall23eebd92010-04-10 09:28:51 +00001894 // If the field is a member of an anonymous struct or union, our key
1895 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001896 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001897 if (RD->isAnonymousStructOrUnion()) {
1898 while (true) {
1899 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1900 if (Parent->isAnonymousStructOrUnion())
1901 RD = Parent;
1902 else
1903 break;
1904 }
1905
Anders Carlsson83ac3122010-03-30 16:19:37 +00001906 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908
Anders Carlssona942dcd2010-03-30 15:39:27 +00001909 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001910}
1911
Anders Carlssone857b292010-04-02 03:37:03 +00001912static void
1913DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001914 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001915 CXXBaseOrMemberInitializer **Inits,
1916 unsigned NumInits) {
1917 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001918 return;
Mike Stump11289f42009-09-09 15:08:12 +00001919
John McCallbb7b6582010-04-10 07:37:23 +00001920 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1921 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001922 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001923
John McCallbb7b6582010-04-10 07:37:23 +00001924 // Build the list of bases and members in the order that they'll
1925 // actually be initialized. The explicit initializers should be in
1926 // this same order but may be missing things.
1927 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00001928
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001929 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1930
John McCallbb7b6582010-04-10 07:37:23 +00001931 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001932 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001933 ClassDecl->vbases_begin(),
1934 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001935 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001936
John McCallbb7b6582010-04-10 07:37:23 +00001937 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001938 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001939 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001940 if (Base->isVirtual())
1941 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001942 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001943 }
Mike Stump11289f42009-09-09 15:08:12 +00001944
John McCallbb7b6582010-04-10 07:37:23 +00001945 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001946 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1947 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00001948 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001949
John McCallbb7b6582010-04-10 07:37:23 +00001950 unsigned NumIdealInits = IdealInitKeys.size();
1951 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00001952
John McCallbb7b6582010-04-10 07:37:23 +00001953 CXXBaseOrMemberInitializer *PrevInit = 0;
1954 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1955 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1956 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1957
1958 // Scan forward to try to find this initializer in the idealized
1959 // initializers list.
1960 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1961 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001962 break;
John McCallbb7b6582010-04-10 07:37:23 +00001963
1964 // If we didn't find this initializer, it must be because we
1965 // scanned past it on a previous iteration. That can only
1966 // happen if we're out of order; emit a warning.
1967 if (IdealIndex == NumIdealInits) {
1968 assert(PrevInit && "initializer not found in initializer list");
1969
1970 Sema::SemaDiagnosticBuilder D =
1971 SemaRef.Diag(PrevInit->getSourceLocation(),
1972 diag::warn_initializer_out_of_order);
1973
1974 if (PrevInit->isMemberInitializer())
1975 D << 0 << PrevInit->getMember()->getDeclName();
1976 else
1977 D << 1 << PrevInit->getBaseClassInfo()->getType();
1978
1979 if (Init->isMemberInitializer())
1980 D << 0 << Init->getMember()->getDeclName();
1981 else
1982 D << 1 << Init->getBaseClassInfo()->getType();
1983
1984 // Move back to the initializer's location in the ideal list.
1985 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1986 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001987 break;
John McCallbb7b6582010-04-10 07:37:23 +00001988
1989 assert(IdealIndex != NumIdealInits &&
1990 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001991 }
John McCallbb7b6582010-04-10 07:37:23 +00001992
1993 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001994 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001995}
1996
John McCall23eebd92010-04-10 09:28:51 +00001997namespace {
1998bool CheckRedundantInit(Sema &S,
1999 CXXBaseOrMemberInitializer *Init,
2000 CXXBaseOrMemberInitializer *&PrevInit) {
2001 if (!PrevInit) {
2002 PrevInit = Init;
2003 return false;
2004 }
2005
2006 if (FieldDecl *Field = Init->getMember())
2007 S.Diag(Init->getSourceLocation(),
2008 diag::err_multiple_mem_initialization)
2009 << Field->getDeclName()
2010 << Init->getSourceRange();
2011 else {
2012 Type *BaseClass = Init->getBaseClass();
2013 assert(BaseClass && "neither field nor base");
2014 S.Diag(Init->getSourceLocation(),
2015 diag::err_multiple_base_initialization)
2016 << QualType(BaseClass, 0)
2017 << Init->getSourceRange();
2018 }
2019 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2020 << 0 << PrevInit->getSourceRange();
2021
2022 return true;
2023}
2024
2025typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2026typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2027
2028bool CheckRedundantUnionInit(Sema &S,
2029 CXXBaseOrMemberInitializer *Init,
2030 RedundantUnionMap &Unions) {
2031 FieldDecl *Field = Init->getMember();
2032 RecordDecl *Parent = Field->getParent();
2033 if (!Parent->isAnonymousStructOrUnion())
2034 return false;
2035
2036 NamedDecl *Child = Field;
2037 do {
2038 if (Parent->isUnion()) {
2039 UnionEntry &En = Unions[Parent];
2040 if (En.first && En.first != Child) {
2041 S.Diag(Init->getSourceLocation(),
2042 diag::err_multiple_mem_union_initialization)
2043 << Field->getDeclName()
2044 << Init->getSourceRange();
2045 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2046 << 0 << En.second->getSourceRange();
2047 return true;
2048 } else if (!En.first) {
2049 En.first = Child;
2050 En.second = Init;
2051 }
2052 }
2053
2054 Child = Parent;
2055 Parent = cast<RecordDecl>(Parent->getDeclContext());
2056 } while (Parent->isAnonymousStructOrUnion());
2057
2058 return false;
2059}
2060}
2061
Anders Carlssone857b292010-04-02 03:37:03 +00002062/// ActOnMemInitializers - Handle the member initializers for a constructor.
2063void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2064 SourceLocation ColonLoc,
2065 MemInitTy **meminits, unsigned NumMemInits,
2066 bool AnyErrors) {
2067 if (!ConstructorDecl)
2068 return;
2069
2070 AdjustDeclIfTemplate(ConstructorDecl);
2071
2072 CXXConstructorDecl *Constructor
2073 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2074
2075 if (!Constructor) {
2076 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2077 return;
2078 }
2079
2080 CXXBaseOrMemberInitializer **MemInits =
2081 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002082
2083 // Mapping for the duplicate initializers check.
2084 // For member initializers, this is keyed with a FieldDecl*.
2085 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002086 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002087
2088 // Mapping for the inconsistent anonymous-union initializers check.
2089 RedundantUnionMap MemberUnions;
2090
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002091 bool HadError = false;
2092 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002093 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002094
John McCall23eebd92010-04-10 09:28:51 +00002095 if (Init->isMemberInitializer()) {
2096 FieldDecl *Field = Init->getMember();
2097 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2098 CheckRedundantUnionInit(*this, Init, MemberUnions))
2099 HadError = true;
2100 } else {
2101 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2102 if (CheckRedundantInit(*this, Init, Members[Key]))
2103 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002104 }
Anders Carlssone857b292010-04-02 03:37:03 +00002105 }
2106
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002107 if (HadError)
2108 return;
2109
Anders Carlssone857b292010-04-02 03:37:03 +00002110 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002111
2112 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002113}
2114
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002115void
John McCalla6309952010-03-16 21:39:52 +00002116Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2117 CXXRecordDecl *ClassDecl) {
2118 // Ignore dependent contexts.
2119 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002120 return;
John McCall1064d7e2010-03-16 05:22:47 +00002121
2122 // FIXME: all the access-control diagnostics are positioned on the
2123 // field/base declaration. That's probably good; that said, the
2124 // user might reasonably want to know why the destructor is being
2125 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002126
Anders Carlssondee9a302009-11-17 04:44:12 +00002127 // Non-static data members.
2128 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2129 E = ClassDecl->field_end(); I != E; ++I) {
2130 FieldDecl *Field = *I;
2131
2132 QualType FieldType = Context.getBaseElementType(Field->getType());
2133
2134 const RecordType* RT = FieldType->getAs<RecordType>();
2135 if (!RT)
2136 continue;
2137
2138 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2139 if (FieldClassDecl->hasTrivialDestructor())
2140 continue;
2141
John McCall1064d7e2010-03-16 05:22:47 +00002142 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2143 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002144 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002145 << Field->getDeclName()
2146 << FieldType);
2147
John McCalla6309952010-03-16 21:39:52 +00002148 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002149 }
2150
John McCall1064d7e2010-03-16 05:22:47 +00002151 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2152
Anders Carlssondee9a302009-11-17 04:44:12 +00002153 // Bases.
2154 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2155 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002156 // Bases are always records in a well-formed non-dependent class.
2157 const RecordType *RT = Base->getType()->getAs<RecordType>();
2158
2159 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002160 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002161 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002162
2163 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002164 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002165 if (BaseClassDecl->hasTrivialDestructor())
2166 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002167
2168 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2169
2170 // FIXME: caret should be on the start of the class name
2171 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002172 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002173 << Base->getType()
2174 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002175
John McCalla6309952010-03-16 21:39:52 +00002176 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002177 }
2178
2179 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002180 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2181 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002182
2183 // Bases are always records in a well-formed non-dependent class.
2184 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2185
2186 // Ignore direct virtual bases.
2187 if (DirectVirtualBases.count(RT))
2188 continue;
2189
Anders Carlssondee9a302009-11-17 04:44:12 +00002190 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002191 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002192 if (BaseClassDecl->hasTrivialDestructor())
2193 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002194
2195 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2196 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002197 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002198 << VBase->getType());
2199
John McCalla6309952010-03-16 21:39:52 +00002200 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002201 }
2202}
2203
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002204void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002205 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002206 return;
Mike Stump11289f42009-09-09 15:08:12 +00002207
Mike Stump11289f42009-09-09 15:08:12 +00002208 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002209 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002210 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002211}
2212
Mike Stump11289f42009-09-09 15:08:12 +00002213bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002214 unsigned DiagID, AbstractDiagSelID SelID,
2215 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002216 if (SelID == -1)
2217 return RequireNonAbstractType(Loc, T,
2218 PDiag(DiagID), CurrentRD);
2219 else
2220 return RequireNonAbstractType(Loc, T,
2221 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002222}
2223
Anders Carlssoneabf7702009-08-27 00:13:57 +00002224bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2225 const PartialDiagnostic &PD,
2226 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002227 if (!getLangOptions().CPlusPlus)
2228 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002229
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002230 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002231 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002232 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002234 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002235 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002236 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002237 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002238
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002239 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002240 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002241 }
Mike Stump11289f42009-09-09 15:08:12 +00002242
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002243 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002244 if (!RT)
2245 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002246
John McCall67da35c2010-02-04 22:26:26 +00002247 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002248
Anders Carlssonb57738b2009-03-24 17:23:42 +00002249 if (CurrentRD && CurrentRD != RD)
2250 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002251
John McCall67da35c2010-02-04 22:26:26 +00002252 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002253 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002254 return false;
2255
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002256 if (!RD->isAbstract())
2257 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002258
Anders Carlssoneabf7702009-08-27 00:13:57 +00002259 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002260
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002261 // Check if we've already emitted the list of pure virtual functions for this
2262 // class.
2263 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2264 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002265
Douglas Gregor4165bd62010-03-23 23:47:56 +00002266 CXXFinalOverriderMap FinalOverriders;
2267 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002268
Douglas Gregor4165bd62010-03-23 23:47:56 +00002269 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2270 MEnd = FinalOverriders.end();
2271 M != MEnd;
2272 ++M) {
2273 for (OverridingMethods::iterator SO = M->second.begin(),
2274 SOEnd = M->second.end();
2275 SO != SOEnd; ++SO) {
2276 // C++ [class.abstract]p4:
2277 // A class is abstract if it contains or inherits at least one
2278 // pure virtual function for which the final overrider is pure
2279 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002280
Douglas Gregor4165bd62010-03-23 23:47:56 +00002281 //
2282 if (SO->second.size() != 1)
2283 continue;
2284
2285 if (!SO->second.front().Method->isPure())
2286 continue;
2287
2288 Diag(SO->second.front().Method->getLocation(),
2289 diag::note_pure_virtual_function)
2290 << SO->second.front().Method->getDeclName();
2291 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002292 }
2293
2294 if (!PureVirtualClassDiagSet)
2295 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2296 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002297
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002298 return true;
2299}
2300
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002301namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002302 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002303 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2304 Sema &SemaRef;
2305 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002306
Anders Carlssonb57738b2009-03-24 17:23:42 +00002307 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002308 bool Invalid = false;
2309
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002310 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2311 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002312 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002313
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002314 return Invalid;
2315 }
Mike Stump11289f42009-09-09 15:08:12 +00002316
Anders Carlssonb57738b2009-03-24 17:23:42 +00002317 public:
2318 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2319 : SemaRef(SemaRef), AbstractClass(ac) {
2320 Visit(SemaRef.Context.getTranslationUnitDecl());
2321 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002322
Anders Carlssonb57738b2009-03-24 17:23:42 +00002323 bool VisitFunctionDecl(const FunctionDecl *FD) {
2324 if (FD->isThisDeclarationADefinition()) {
2325 // No need to do the check if we're in a definition, because it requires
2326 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002327 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002328 return VisitDeclContext(FD);
2329 }
Mike Stump11289f42009-09-09 15:08:12 +00002330
Anders Carlssonb57738b2009-03-24 17:23:42 +00002331 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002332 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002333 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002334 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2335 diag::err_abstract_type_in_decl,
2336 Sema::AbstractReturnType,
2337 AbstractClass);
2338
Mike Stump11289f42009-09-09 15:08:12 +00002339 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002340 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002341 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002342 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002343 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002344 VD->getOriginalType(),
2345 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002346 Sema::AbstractParamType,
2347 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002348 }
2349
2350 return Invalid;
2351 }
Mike Stump11289f42009-09-09 15:08:12 +00002352
Anders Carlssonb57738b2009-03-24 17:23:42 +00002353 bool VisitDecl(const Decl* D) {
2354 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2355 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002356
Anders Carlssonb57738b2009-03-24 17:23:42 +00002357 return false;
2358 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002359 };
2360}
2361
Douglas Gregorc99f1552009-12-03 18:33:45 +00002362/// \brief Perform semantic checks on a class definition that has been
2363/// completing, introducing implicitly-declared members, checking for
2364/// abstract types, etc.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002365void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002366 if (!Record || Record->isInvalidDecl())
2367 return;
2368
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002369 if (!Record->isDependentType())
Douglas Gregorb93b6062010-04-12 17:09:20 +00002370 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002371
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002372 if (Record->isInvalidDecl())
2373 return;
2374
John McCall2cb94162010-01-28 07:38:46 +00002375 // Set access bits correctly on the directly-declared conversions.
2376 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2377 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2378 Convs->setAccess(I, (*I)->getAccess());
2379
Douglas Gregor4165bd62010-03-23 23:47:56 +00002380 // Determine whether we need to check for final overriders. We do
2381 // this either when there are virtual base classes (in which case we
2382 // may end up finding multiple final overriders for a given virtual
2383 // function) or any of the base classes is abstract (in which case
2384 // we might detect that this class is abstract).
2385 bool CheckFinalOverriders = false;
2386 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2387 !Record->isDependentType()) {
2388 if (Record->getNumVBases())
2389 CheckFinalOverriders = true;
2390 else if (!Record->isAbstract()) {
2391 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2392 BEnd = Record->bases_end();
2393 B != BEnd; ++B) {
2394 CXXRecordDecl *BaseDecl
2395 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2396 if (BaseDecl->isAbstract()) {
2397 CheckFinalOverriders = true;
2398 break;
2399 }
2400 }
2401 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002402 }
2403
Douglas Gregor4165bd62010-03-23 23:47:56 +00002404 if (CheckFinalOverriders) {
2405 CXXFinalOverriderMap FinalOverriders;
2406 Record->getFinalOverriders(FinalOverriders);
2407
2408 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2409 MEnd = FinalOverriders.end();
2410 M != MEnd; ++M) {
2411 for (OverridingMethods::iterator SO = M->second.begin(),
2412 SOEnd = M->second.end();
2413 SO != SOEnd; ++SO) {
2414 assert(SO->second.size() > 0 &&
2415 "All virtual functions have overridding virtual functions");
2416 if (SO->second.size() == 1) {
2417 // C++ [class.abstract]p4:
2418 // A class is abstract if it contains or inherits at least one
2419 // pure virtual function for which the final overrider is pure
2420 // virtual.
2421 if (SO->second.front().Method->isPure())
2422 Record->setAbstract(true);
2423 continue;
2424 }
2425
2426 // C++ [class.virtual]p2:
2427 // In a derived class, if a virtual member function of a base
2428 // class subobject has more than one final overrider the
2429 // program is ill-formed.
2430 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2431 << (NamedDecl *)M->first << Record;
2432 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2433 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2434 OMEnd = SO->second.end();
2435 OM != OMEnd; ++OM)
2436 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2437 << (NamedDecl *)M->first << OM->Method->getParent();
2438
2439 Record->setInvalidDecl();
2440 }
2441 }
2442 }
2443
2444 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregorc99f1552009-12-03 18:33:45 +00002445 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-04-15 00:00:53 +00002446
2447 // If this is not an aggregate type and has no user-declared constructor,
2448 // complain about any non-static data members of reference or const scalar
2449 // type, since they will never get initializers.
2450 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2451 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2452 bool Complained = false;
2453 for (RecordDecl::field_iterator F = Record->field_begin(),
2454 FEnd = Record->field_end();
2455 F != FEnd; ++F) {
2456 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002457 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002458 if (!Complained) {
2459 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2460 << Record->getTagKind() << Record;
2461 Complained = true;
2462 }
2463
2464 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2465 << F->getType()->isReferenceType()
2466 << F->getDeclName();
2467 }
2468 }
2469 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002470}
2471
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002472void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002473 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002474 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002475 SourceLocation RBrac,
2476 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002477 if (!TagDecl)
2478 return;
Mike Stump11289f42009-09-09 15:08:12 +00002479
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002480 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002481
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002482 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002483 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002484 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002485
Douglas Gregorb93b6062010-04-12 17:09:20 +00002486 CheckCompletedCXXClass(S,
Douglas Gregorc99f1552009-12-03 18:33:45 +00002487 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002488}
2489
Douglas Gregor05379422008-11-03 17:51:48 +00002490/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2491/// special functions, such as the default constructor, copy
2492/// constructor, or destructor, to the given C++ class (C++
2493/// [special]p1). This routine can only be executed just before the
2494/// definition of the class is complete.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002495///
2496/// The scope, if provided, is the class scope.
2497void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2498 CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002499 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002500 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002501
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002502 // FIXME: Implicit declarations have exception specifications, which are
2503 // the union of the specifications of the implicitly called functions.
2504
Douglas Gregor05379422008-11-03 17:51:48 +00002505 if (!ClassDecl->hasUserDeclaredConstructor()) {
2506 // C++ [class.ctor]p5:
2507 // A default constructor for a class X is a constructor of class X
2508 // that can be called without an argument. If there is no
2509 // user-declared constructor for class X, a default constructor is
2510 // implicitly declared. An implicitly-declared default constructor
2511 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002512 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002513 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002514 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002515 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002516 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002517 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002518 0, 0, false, 0,
2519 /*FIXME*/false, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002520 0, 0,
2521 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002522 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002523 /*isExplicit=*/false,
2524 /*isInline=*/true,
2525 /*isImplicitlyDeclared=*/true);
2526 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002527 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002528 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002529 if (S)
2530 PushOnScopeChains(DefaultCon, S, true);
2531 else
2532 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002533 }
2534
2535 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2536 // C++ [class.copy]p4:
2537 // If the class definition does not explicitly declare a copy
2538 // constructor, one is declared implicitly.
2539
2540 // C++ [class.copy]p5:
2541 // The implicitly-declared copy constructor for a class X will
2542 // have the form
2543 //
2544 // X::X(const X&)
2545 //
2546 // if
2547 bool HasConstCopyConstructor = true;
2548
2549 // -- each direct or virtual base class B of X has a copy
2550 // constructor whose first parameter is of type const B& or
2551 // const volatile B&, and
2552 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2553 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2554 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002555 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002556 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002557 = BaseClassDecl->hasConstCopyConstructor(Context);
2558 }
2559
2560 // -- for all the nonstatic data members of X that are of a
2561 // class type M (or array thereof), each such class type
2562 // has a copy constructor whose first parameter is of type
2563 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002564 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2565 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002566 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002567 QualType FieldType = (*Field)->getType();
2568 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2569 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002570 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002571 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002572 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002573 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002574 = FieldClassDecl->hasConstCopyConstructor(Context);
2575 }
2576 }
2577
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002578 // Otherwise, the implicitly declared copy constructor will have
2579 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002580 //
2581 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002582 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002583 if (HasConstCopyConstructor)
2584 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002585 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002586
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002587 // An implicitly-declared copy constructor is an inline public
2588 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002589 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002590 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002591 CXXConstructorDecl *CopyConstructor
2592 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002593 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002594 Context.getFunctionType(Context.VoidTy,
2595 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002596 false, 0,
2597 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002598 false, 0, 0,
2599 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002600 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002601 /*isExplicit=*/false,
2602 /*isInline=*/true,
2603 /*isImplicitlyDeclared=*/true);
2604 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002605 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002606 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002607
2608 // Add the parameter to the constructor.
2609 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2610 ClassDecl->getLocation(),
2611 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002612 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002613 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002614 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002615 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregorb93b6062010-04-12 17:09:20 +00002616 if (S)
2617 PushOnScopeChains(CopyConstructor, S, true);
2618 else
2619 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002620 }
2621
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002622 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2623 // Note: The following rules are largely analoguous to the copy
2624 // constructor rules. Note that virtual bases are not taken into account
2625 // for determining the argument type of the operator. Note also that
2626 // operators taking an object instead of a reference are allowed.
2627 //
2628 // C++ [class.copy]p10:
2629 // If the class definition does not explicitly declare a copy
2630 // assignment operator, one is declared implicitly.
2631 // The implicitly-defined copy assignment operator for a class X
2632 // will have the form
2633 //
2634 // X& X::operator=(const X&)
2635 //
2636 // if
2637 bool HasConstCopyAssignment = true;
2638
2639 // -- each direct base class B of X has a copy assignment operator
2640 // whose parameter is of type const B&, const volatile B& or B,
2641 // and
2642 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2643 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002644 assert(!Base->getType()->isDependentType() &&
2645 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002646 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002647 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002648 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002649 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002650 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002651 }
2652
2653 // -- for all the nonstatic data members of X that are of a class
2654 // type M (or array thereof), each such class type has a copy
2655 // assignment operator whose parameter is of type const M&,
2656 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002657 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2658 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002659 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002660 QualType FieldType = (*Field)->getType();
2661 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2662 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002663 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002664 const CXXRecordDecl *FieldClassDecl
2665 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002666 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002667 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002668 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002669 }
2670 }
2671
2672 // Otherwise, the implicitly declared copy assignment operator will
2673 // have the form
2674 //
2675 // X& X::operator=(X&)
2676 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002677 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002678 if (HasConstCopyAssignment)
2679 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002680 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002681
2682 // An implicitly-declared copy assignment operator is an inline public
2683 // member of its class.
2684 DeclarationName Name =
2685 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2686 CXXMethodDecl *CopyAssignment =
2687 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2688 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002689 false, 0,
2690 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002691 false, 0, 0,
2692 FunctionType::ExtInfo()),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002693 /*TInfo=*/0, /*isStatic=*/false,
2694 /*StorageClassAsWritten=*/FunctionDecl::None,
2695 /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002696 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002697 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002698 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002699 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002700
2701 // Add the parameter to the operator.
2702 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2703 ClassDecl->getLocation(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00002704 /*Id=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002705 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002706 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002707 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002708 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002709
2710 // Don't call addedAssignmentOperator. There is no way to distinguish an
2711 // implicit from an explicit assignment operator.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002712 if (S)
2713 PushOnScopeChains(CopyAssignment, S, true);
2714 else
2715 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002716 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002717 }
2718
Douglas Gregor1349b452008-12-15 21:24:18 +00002719 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002720 // C++ [class.dtor]p2:
2721 // If a class has no user-declared destructor, a destructor is
2722 // declared implicitly. An implicitly-declared destructor is an
2723 // inline public member of its class.
John McCall58f10c32010-03-11 09:03:00 +00002724 QualType Ty = Context.getFunctionType(Context.VoidTy,
2725 0, 0, false, 0,
2726 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002727 false, 0, 0, FunctionType::ExtInfo());
John McCall58f10c32010-03-11 09:03:00 +00002728
Mike Stump11289f42009-09-09 15:08:12 +00002729 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002730 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002731 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002732 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall58f10c32010-03-11 09:03:00 +00002733 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002734 /*isInline=*/true,
2735 /*isImplicitlyDeclared=*/true);
2736 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002737 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002738 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002739 if (S)
2740 PushOnScopeChains(Destructor, S, true);
2741 else
2742 ClassDecl->addDecl(Destructor);
John McCall58f10c32010-03-11 09:03:00 +00002743
2744 // This could be uniqued if it ever proves significant.
2745 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002746
2747 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002748 }
Douglas Gregor05379422008-11-03 17:51:48 +00002749}
2750
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002751void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002752 Decl *D = TemplateD.getAs<Decl>();
2753 if (!D)
2754 return;
2755
2756 TemplateParameterList *Params = 0;
2757 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2758 Params = Template->getTemplateParameters();
2759 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2760 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2761 Params = PartialSpec->getTemplateParameters();
2762 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002763 return;
2764
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002765 for (TemplateParameterList::iterator Param = Params->begin(),
2766 ParamEnd = Params->end();
2767 Param != ParamEnd; ++Param) {
2768 NamedDecl *Named = cast<NamedDecl>(*Param);
2769 if (Named->getDeclName()) {
2770 S->AddDecl(DeclPtrTy::make(Named));
2771 IdResolver.AddDecl(Named);
2772 }
2773 }
2774}
2775
John McCall6df5fef2009-12-19 10:49:29 +00002776void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2777 if (!RecordD) return;
2778 AdjustDeclIfTemplate(RecordD);
2779 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2780 PushDeclContext(S, Record);
2781}
2782
2783void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2784 if (!RecordD) return;
2785 PopDeclContext();
2786}
2787
Douglas Gregor4d87df52008-12-16 21:30:33 +00002788/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2789/// parsing a top-level (non-nested) C++ class, and we are now
2790/// parsing those parts of the given Method declaration that could
2791/// not be parsed earlier (C++ [class.mem]p2), such as default
2792/// arguments. This action should enter the scope of the given
2793/// Method declaration as if we had just parsed the qualified method
2794/// name. However, it should not bring the parameters into scope;
2795/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002796void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002797}
2798
2799/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2800/// C++ method declaration. We're (re-)introducing the given
2801/// function parameter into scope for use in parsing later parts of
2802/// the method declaration. For example, we could see an
2803/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002804void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002805 if (!ParamD)
2806 return;
Mike Stump11289f42009-09-09 15:08:12 +00002807
Chris Lattner83f095c2009-03-28 19:18:32 +00002808 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002809
2810 // If this parameter has an unparsed default argument, clear it out
2811 // to make way for the parsed default argument.
2812 if (Param->hasUnparsedDefaultArg())
2813 Param->setDefaultArg(0);
2814
Chris Lattner83f095c2009-03-28 19:18:32 +00002815 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002816 if (Param->getDeclName())
2817 IdResolver.AddDecl(Param);
2818}
2819
2820/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2821/// processing the delayed method declaration for Method. The method
2822/// declaration is now considered finished. There may be a separate
2823/// ActOnStartOfFunctionDef action later (not necessarily
2824/// immediately!) for this method, if it was also defined inside the
2825/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002826void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002827 if (!MethodD)
2828 return;
Mike Stump11289f42009-09-09 15:08:12 +00002829
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002830 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002831
Chris Lattner83f095c2009-03-28 19:18:32 +00002832 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002833
2834 // Now that we have our default arguments, check the constructor
2835 // again. It could produce additional diagnostics or affect whether
2836 // the class has implicitly-declared destructors, among other
2837 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002838 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2839 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002840
2841 // Check the default arguments, which we may have added.
2842 if (!Method->isInvalidDecl())
2843 CheckCXXDefaultArguments(Method);
2844}
2845
Douglas Gregor831c93f2008-11-05 20:51:48 +00002846/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002847/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002848/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002849/// emit diagnostics and set the invalid bit to true. In any case, the type
2850/// will be updated to reflect a well-formed type for the constructor and
2851/// returned.
2852QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2853 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002854 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002855
2856 // C++ [class.ctor]p3:
2857 // A constructor shall not be virtual (10.3) or static (9.4). A
2858 // constructor can be invoked for a const, volatile or const
2859 // volatile object. A constructor shall not be declared const,
2860 // volatile, or const volatile (9.3.2).
2861 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002862 if (!D.isInvalidType())
2863 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2864 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2865 << SourceRange(D.getIdentifierLoc());
2866 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002867 }
2868 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002869 if (!D.isInvalidType())
2870 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2871 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2872 << SourceRange(D.getIdentifierLoc());
2873 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002874 SC = FunctionDecl::None;
2875 }
Mike Stump11289f42009-09-09 15:08:12 +00002876
Chris Lattner38378bf2009-04-25 08:28:21 +00002877 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2878 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002879 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002880 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2881 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002882 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002883 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2884 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002885 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002886 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2887 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
Douglas Gregor831c93f2008-11-05 20:51:48 +00002890 // Rebuild the function type "R" without any type qualifiers (in
2891 // case any of the errors above fired) and with "void" as the
2892 // return type, since constructors don't have return types. We
2893 // *always* have to do this, because GetTypeForDeclarator will
2894 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002895 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002896 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2897 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002898 Proto->isVariadic(), 0,
2899 Proto->hasExceptionSpec(),
2900 Proto->hasAnyExceptionSpec(),
2901 Proto->getNumExceptions(),
2902 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002903 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002904}
2905
Douglas Gregor4d87df52008-12-16 21:30:33 +00002906/// CheckConstructor - Checks a fully-formed constructor for
2907/// well-formedness, issuing any diagnostics required. Returns true if
2908/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002909void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002910 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002911 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2912 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002913 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002914
2915 // C++ [class.copy]p3:
2916 // A declaration of a constructor for a class X is ill-formed if
2917 // its first parameter is of type (optionally cv-qualified) X and
2918 // either there are no other parameters or else all other
2919 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002920 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002921 ((Constructor->getNumParams() == 1) ||
2922 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002923 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2924 Constructor->getTemplateSpecializationKind()
2925 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002926 QualType ParamType = Constructor->getParamDecl(0)->getType();
2927 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2928 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002929 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2930 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregora771f462010-03-31 17:46:05 +00002931 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002932
2933 // FIXME: Rather that making the constructor invalid, we should endeavor
2934 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002935 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002936 }
2937 }
Mike Stump11289f42009-09-09 15:08:12 +00002938
John McCall43314ab2010-04-13 07:45:41 +00002939 // Notify the class that we've added a constructor. In principle we
2940 // don't need to do this for out-of-line declarations; in practice
2941 // we only instantiate the most recent declaration of a method, so
2942 // we have to call this for everything but friends.
2943 if (!Constructor->getFriendObjectKind())
2944 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002945}
2946
Anders Carlsson26a807d2009-11-30 21:24:50 +00002947/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2948/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002949bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002950 CXXRecordDecl *RD = Destructor->getParent();
2951
2952 if (Destructor->isVirtual()) {
2953 SourceLocation Loc;
2954
2955 if (!Destructor->isImplicit())
2956 Loc = Destructor->getLocation();
2957 else
2958 Loc = RD->getLocation();
2959
2960 // If we have a virtual destructor, look up the deallocation function
2961 FunctionDecl *OperatorDelete = 0;
2962 DeclarationName Name =
2963 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002964 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002965 return true;
2966
2967 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002968 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002969
2970 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002971}
2972
Mike Stump11289f42009-09-09 15:08:12 +00002973static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002974FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2975 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2976 FTI.ArgInfo[0].Param &&
2977 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2978}
2979
Douglas Gregor831c93f2008-11-05 20:51:48 +00002980/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2981/// the well-formednes of the destructor declarator @p D with type @p
2982/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002983/// emit diagnostics and set the declarator to invalid. Even if this happens,
2984/// will be updated to reflect a well-formed type for the destructor and
2985/// returned.
2986QualType Sema::CheckDestructorDeclarator(Declarator &D,
2987 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002988 // C++ [class.dtor]p1:
2989 // [...] A typedef-name that names a class is a class-name
2990 // (7.1.3); however, a typedef-name that names a class shall not
2991 // be used as the identifier in the declarator for a destructor
2992 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002993 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002994 if (isa<TypedefType>(DeclaratorType)) {
2995 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002996 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002997 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002998 }
2999
3000 // C++ [class.dtor]p2:
3001 // A destructor is used to destroy objects of its class type. A
3002 // destructor takes no parameters, and no return type can be
3003 // specified for it (not even void). The address of a destructor
3004 // shall not be taken. A destructor shall not be static. A
3005 // destructor can be invoked for a const, volatile or const
3006 // volatile object. A destructor shall not be declared const,
3007 // volatile or const volatile (9.3.2).
3008 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003009 if (!D.isInvalidType())
3010 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3011 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3012 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003013 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00003014 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003015 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003016 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003017 // Destructors don't have return types, but the parser will
3018 // happily parse something like:
3019 //
3020 // class X {
3021 // float ~X();
3022 // };
3023 //
3024 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003025 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3026 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3027 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029
Chris Lattner38378bf2009-04-25 08:28:21 +00003030 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3031 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003032 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003033 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3034 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003035 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003036 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3037 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003038 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003039 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3040 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003041 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003042 }
3043
3044 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003045 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003046 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3047
3048 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003049 FTI.freeArgs();
3050 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003051 }
3052
Mike Stump11289f42009-09-09 15:08:12 +00003053 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003054 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003055 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003056 D.setInvalidType();
3057 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003058
3059 // Rebuild the function type "R" without any type qualifiers or
3060 // parameters (in case any of the errors above fired) and with
3061 // "void" as the return type, since destructors don't have return
3062 // types. We *always* have to do this, because GetTypeForDeclarator
3063 // will put in a result type of "int" when none was specified.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003064 // FIXME: Exceptions!
3065 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003066 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003067}
3068
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003069/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3070/// well-formednes of the conversion function declarator @p D with
3071/// type @p R. If there are any errors in the declarator, this routine
3072/// will emit diagnostics and return true. Otherwise, it will return
3073/// false. Either way, the type @p R will be updated to reflect a
3074/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003075void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003076 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003077 // C++ [class.conv.fct]p1:
3078 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003079 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003080 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003081 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003082 if (!D.isInvalidType())
3083 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3084 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3085 << SourceRange(D.getIdentifierLoc());
3086 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003087 SC = FunctionDecl::None;
3088 }
John McCall212fa2e2010-04-13 00:04:31 +00003089
3090 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3091
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003092 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003093 // Conversion functions don't have return types, but the parser will
3094 // happily parse something like:
3095 //
3096 // class X {
3097 // float operator bool();
3098 // };
3099 //
3100 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003101 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3102 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3103 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003104 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003105 }
3106
John McCall212fa2e2010-04-13 00:04:31 +00003107 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3108
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003109 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003110 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003111 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3112
3113 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003114 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003115 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003116 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003117 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003118 D.setInvalidType();
3119 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003120
John McCall212fa2e2010-04-13 00:04:31 +00003121 // Diagnose "&operator bool()" and other such nonsense. This
3122 // is actually a gcc extension which we don't support.
3123 if (Proto->getResultType() != ConvType) {
3124 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3125 << Proto->getResultType();
3126 D.setInvalidType();
3127 ConvType = Proto->getResultType();
3128 }
3129
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003130 // C++ [class.conv.fct]p4:
3131 // The conversion-type-id shall not represent a function type nor
3132 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003133 if (ConvType->isArrayType()) {
3134 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3135 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003136 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003137 } else if (ConvType->isFunctionType()) {
3138 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3139 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003140 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003141 }
3142
3143 // Rebuild the function type "R" without any parameters (in case any
3144 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003145 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003146 if (D.isInvalidType()) {
3147 R = Context.getFunctionType(ConvType, 0, 0, false,
3148 Proto->getTypeQuals(),
3149 Proto->hasExceptionSpec(),
3150 Proto->hasAnyExceptionSpec(),
3151 Proto->getNumExceptions(),
3152 Proto->exception_begin(),
3153 Proto->getExtInfo());
3154 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003155
Douglas Gregor5fb53972009-01-14 15:45:31 +00003156 // C++0x explicit conversion operators.
3157 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003158 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003159 diag::warn_explicit_conversion_functions)
3160 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003161}
3162
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003163/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3164/// the declaration of the given C++ conversion function. This routine
3165/// is responsible for recording the conversion function in the C++
3166/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00003167Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003168 assert(Conversion && "Expected to receive a conversion function declaration");
3169
Douglas Gregor4287b372008-12-12 08:25:50 +00003170 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003171
3172 // Make sure we aren't redeclaring the conversion function.
3173 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003174
3175 // C++ [class.conv.fct]p1:
3176 // [...] A conversion function is never used to convert a
3177 // (possibly cv-qualified) object to the (possibly cv-qualified)
3178 // same object type (or a reference to it), to a (possibly
3179 // cv-qualified) base class of that type (or a reference to it),
3180 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003181 // FIXME: Suppress this warning if the conversion function ends up being a
3182 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003183 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003184 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003185 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003186 ConvType = ConvTypeRef->getPointeeType();
3187 if (ConvType->isRecordType()) {
3188 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3189 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003190 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003191 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003192 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003193 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003194 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003195 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003196 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003197 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003198 }
3199
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003200 if (Conversion->getPrimaryTemplate()) {
3201 // ignore specializations
3202 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003203 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003204 = Conversion->getDescribedFunctionTemplate()) {
3205 if (ClassDecl->replaceConversion(
3206 ConversionTemplate->getPreviousDeclaration(),
3207 ConversionTemplate))
3208 return DeclPtrTy::make(ConversionTemplate);
3209 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3210 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00003211 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003212 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003213 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003214 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003215 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003216 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003217 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003218
Chris Lattner83f095c2009-03-28 19:18:32 +00003219 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003220}
3221
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003222//===----------------------------------------------------------------------===//
3223// Namespace Handling
3224//===----------------------------------------------------------------------===//
3225
3226/// ActOnStartNamespaceDef - This is called at the start of a namespace
3227/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00003228Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3229 SourceLocation IdentLoc,
3230 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003231 SourceLocation LBrace,
3232 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003233 NamespaceDecl *Namespc =
3234 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3235 Namespc->setLBracLoc(LBrace);
3236
3237 Scope *DeclRegionScope = NamespcScope->getParent();
3238
Anders Carlssona7bcade2010-02-07 01:09:23 +00003239 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3240
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003241 if (II) {
3242 // C++ [namespace.def]p2:
3243 // The identifier in an original-namespace-definition shall not have been
3244 // previously defined in the declarative region in which the
3245 // original-namespace-definition appears. The identifier in an
3246 // original-namespace-definition is the name of the namespace. Subsequently
3247 // in that declarative region, it is treated as an original-namespace-name.
3248
John McCall9f3059a2009-10-09 21:13:30 +00003249 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003250 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003251 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003252
Douglas Gregor91f84212008-12-11 16:49:14 +00003253 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3254 // This is an extended namespace definition.
3255 // Attach this namespace decl to the chain of extended namespace
3256 // definitions.
3257 OrigNS->setNextNamespace(Namespc);
3258 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003259
Mike Stump11289f42009-09-09 15:08:12 +00003260 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003261 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003262 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003263 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003264 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003265 } else if (PrevDecl) {
3266 // This is an invalid name redefinition.
3267 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3268 << Namespc->getDeclName();
3269 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3270 Namespc->setInvalidDecl();
3271 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003272 } else if (II->isStr("std") &&
3273 CurContext->getLookupContext()->isTranslationUnit()) {
3274 // This is the first "real" definition of the namespace "std", so update
3275 // our cache of the "std" namespace to point at this definition.
3276 if (StdNamespace) {
3277 // We had already defined a dummy namespace "std". Link this new
3278 // namespace definition to the dummy namespace "std".
3279 StdNamespace->setNextNamespace(Namespc);
3280 StdNamespace->setLocation(IdentLoc);
3281 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3282 }
3283
3284 // Make our StdNamespace cache point at the first real definition of the
3285 // "std" namespace.
3286 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003287 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003288
3289 PushOnScopeChains(Namespc, DeclRegionScope);
3290 } else {
John McCall4fa53422009-10-01 00:25:31 +00003291 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003292 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003293
3294 // Link the anonymous namespace into its parent.
3295 NamespaceDecl *PrevDecl;
3296 DeclContext *Parent = CurContext->getLookupContext();
3297 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3298 PrevDecl = TU->getAnonymousNamespace();
3299 TU->setAnonymousNamespace(Namespc);
3300 } else {
3301 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3302 PrevDecl = ND->getAnonymousNamespace();
3303 ND->setAnonymousNamespace(Namespc);
3304 }
3305
3306 // Link the anonymous namespace with its previous declaration.
3307 if (PrevDecl) {
3308 assert(PrevDecl->isAnonymousNamespace());
3309 assert(!PrevDecl->getNextNamespace());
3310 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3311 PrevDecl->setNextNamespace(Namespc);
3312 }
John McCall4fa53422009-10-01 00:25:31 +00003313
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003314 CurContext->addDecl(Namespc);
3315
John McCall4fa53422009-10-01 00:25:31 +00003316 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3317 // behaves as if it were replaced by
3318 // namespace unique { /* empty body */ }
3319 // using namespace unique;
3320 // namespace unique { namespace-body }
3321 // where all occurrences of 'unique' in a translation unit are
3322 // replaced by the same identifier and this identifier differs
3323 // from all other identifiers in the entire program.
3324
3325 // We just create the namespace with an empty name and then add an
3326 // implicit using declaration, just like the standard suggests.
3327 //
3328 // CodeGen enforces the "universally unique" aspect by giving all
3329 // declarations semantically contained within an anonymous
3330 // namespace internal linkage.
3331
John McCall0db42252009-12-16 02:06:49 +00003332 if (!PrevDecl) {
3333 UsingDirectiveDecl* UD
3334 = UsingDirectiveDecl::Create(Context, CurContext,
3335 /* 'using' */ LBrace,
3336 /* 'namespace' */ SourceLocation(),
3337 /* qualifier */ SourceRange(),
3338 /* NNS */ NULL,
3339 /* identifier */ SourceLocation(),
3340 Namespc,
3341 /* Ancestor */ CurContext);
3342 UD->setImplicit();
3343 CurContext->addDecl(UD);
3344 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003345 }
3346
3347 // Although we could have an invalid decl (i.e. the namespace name is a
3348 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003349 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3350 // for the namespace has the declarations that showed up in that particular
3351 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003352 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003353 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003354}
3355
Sebastian Redla6602e92009-11-23 15:34:23 +00003356/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3357/// is a namespace alias, returns the namespace it points to.
3358static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3359 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3360 return AD->getNamespace();
3361 return dyn_cast_or_null<NamespaceDecl>(D);
3362}
3363
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003364/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3365/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003366void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3367 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003368 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3369 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3370 Namespc->setRBracLoc(RBrace);
3371 PopDeclContext();
3372}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003373
Chris Lattner83f095c2009-03-28 19:18:32 +00003374Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3375 SourceLocation UsingLoc,
3376 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003377 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003378 SourceLocation IdentLoc,
3379 IdentifierInfo *NamespcName,
3380 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003381 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3382 assert(NamespcName && "Invalid NamespcName.");
3383 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003384 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003385
Douglas Gregor889ceb72009-02-03 19:21:40 +00003386 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003387
Douglas Gregor34074322009-01-14 22:20:51 +00003388 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003389 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3390 LookupParsedName(R, S, &SS);
3391 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003392 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003393
John McCall9f3059a2009-10-09 21:13:30 +00003394 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003395 NamedDecl *Named = R.getFoundDecl();
3396 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3397 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003398 // C++ [namespace.udir]p1:
3399 // A using-directive specifies that the names in the nominated
3400 // namespace can be used in the scope in which the
3401 // using-directive appears after the using-directive. During
3402 // unqualified name lookup (3.4.1), the names appear as if they
3403 // were declared in the nearest enclosing namespace which
3404 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003405 // namespace. [Note: in this context, "contains" means "contains
3406 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003407
3408 // Find enclosing context containing both using-directive and
3409 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003410 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003411 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3412 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3413 CommonAncestor = CommonAncestor->getParent();
3414
Sebastian Redla6602e92009-11-23 15:34:23 +00003415 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003416 SS.getRange(),
3417 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003418 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003419 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003420 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003421 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003422 }
3423
Douglas Gregor889ceb72009-02-03 19:21:40 +00003424 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003425 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003426 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003427}
3428
3429void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3430 // If scope has associated entity, then using directive is at namespace
3431 // or translation unit scope. We add UsingDirectiveDecls, into
3432 // it's lookup structure.
3433 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003434 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003435 else
3436 // Otherwise it is block-sope. using-directives will affect lookup
3437 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003438 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003439}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003440
Douglas Gregorfec52632009-06-20 00:51:54 +00003441
3442Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003443 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003444 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003445 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003446 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003447 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003448 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003449 bool IsTypeName,
3450 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003451 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregor220f4272009-11-04 16:30:06 +00003453 switch (Name.getKind()) {
3454 case UnqualifiedId::IK_Identifier:
3455 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003456 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003457 case UnqualifiedId::IK_ConversionFunctionId:
3458 break;
3459
3460 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003461 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003462 // C++0x inherited constructors.
3463 if (getLangOptions().CPlusPlus0x) break;
3464
Douglas Gregor220f4272009-11-04 16:30:06 +00003465 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3466 << SS.getRange();
3467 return DeclPtrTy();
3468
3469 case UnqualifiedId::IK_DestructorName:
3470 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3471 << SS.getRange();
3472 return DeclPtrTy();
3473
3474 case UnqualifiedId::IK_TemplateId:
3475 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3476 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3477 return DeclPtrTy();
3478 }
3479
3480 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003481 if (!TargetName)
3482 return DeclPtrTy();
3483
John McCalla0097262009-12-11 02:10:03 +00003484 // Warn about using declarations.
3485 // TODO: store that the declaration was written without 'using' and
3486 // talk about access decls instead of using decls in the
3487 // diagnostics.
3488 if (!HasUsingKeyword) {
3489 UsingLoc = Name.getSourceRange().getBegin();
3490
3491 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003492 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003493 }
3494
John McCall3f746822009-11-17 05:59:44 +00003495 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003496 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003497 TargetName, AttrList,
3498 /* IsInstantiation */ false,
3499 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003500 if (UD)
3501 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003502
Anders Carlsson696a3f12009-08-28 05:40:36 +00003503 return DeclPtrTy::make(UD);
3504}
3505
John McCall84d87672009-12-10 09:41:52 +00003506/// Determines whether to create a using shadow decl for a particular
3507/// decl, given the set of decls existing prior to this using lookup.
3508bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3509 const LookupResult &Previous) {
3510 // Diagnose finding a decl which is not from a base class of the
3511 // current class. We do this now because there are cases where this
3512 // function will silently decide not to build a shadow decl, which
3513 // will pre-empt further diagnostics.
3514 //
3515 // We don't need to do this in C++0x because we do the check once on
3516 // the qualifier.
3517 //
3518 // FIXME: diagnose the following if we care enough:
3519 // struct A { int foo; };
3520 // struct B : A { using A::foo; };
3521 // template <class T> struct C : A {};
3522 // template <class T> struct D : C<T> { using B::foo; } // <---
3523 // This is invalid (during instantiation) in C++03 because B::foo
3524 // resolves to the using decl in B, which is not a base class of D<T>.
3525 // We can't diagnose it immediately because C<T> is an unknown
3526 // specialization. The UsingShadowDecl in D<T> then points directly
3527 // to A::foo, which will look well-formed when we instantiate.
3528 // The right solution is to not collapse the shadow-decl chain.
3529 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3530 DeclContext *OrigDC = Orig->getDeclContext();
3531
3532 // Handle enums and anonymous structs.
3533 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3534 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3535 while (OrigRec->isAnonymousStructOrUnion())
3536 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3537
3538 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3539 if (OrigDC == CurContext) {
3540 Diag(Using->getLocation(),
3541 diag::err_using_decl_nested_name_specifier_is_current_class)
3542 << Using->getNestedNameRange();
3543 Diag(Orig->getLocation(), diag::note_using_decl_target);
3544 return true;
3545 }
3546
3547 Diag(Using->getNestedNameRange().getBegin(),
3548 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3549 << Using->getTargetNestedNameDecl()
3550 << cast<CXXRecordDecl>(CurContext)
3551 << Using->getNestedNameRange();
3552 Diag(Orig->getLocation(), diag::note_using_decl_target);
3553 return true;
3554 }
3555 }
3556
3557 if (Previous.empty()) return false;
3558
3559 NamedDecl *Target = Orig;
3560 if (isa<UsingShadowDecl>(Target))
3561 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3562
John McCalla17e83e2009-12-11 02:33:26 +00003563 // If the target happens to be one of the previous declarations, we
3564 // don't have a conflict.
3565 //
3566 // FIXME: but we might be increasing its access, in which case we
3567 // should redeclare it.
3568 NamedDecl *NonTag = 0, *Tag = 0;
3569 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3570 I != E; ++I) {
3571 NamedDecl *D = (*I)->getUnderlyingDecl();
3572 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3573 return false;
3574
3575 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3576 }
3577
John McCall84d87672009-12-10 09:41:52 +00003578 if (Target->isFunctionOrFunctionTemplate()) {
3579 FunctionDecl *FD;
3580 if (isa<FunctionTemplateDecl>(Target))
3581 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3582 else
3583 FD = cast<FunctionDecl>(Target);
3584
3585 NamedDecl *OldDecl = 0;
3586 switch (CheckOverload(FD, Previous, OldDecl)) {
3587 case Ovl_Overload:
3588 return false;
3589
3590 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003591 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003592 break;
3593
3594 // We found a decl with the exact signature.
3595 case Ovl_Match:
3596 if (isa<UsingShadowDecl>(OldDecl)) {
3597 // Silently ignore the possible conflict.
3598 return false;
3599 }
3600
3601 // If we're in a record, we want to hide the target, so we
3602 // return true (without a diagnostic) to tell the caller not to
3603 // build a shadow decl.
3604 if (CurContext->isRecord())
3605 return true;
3606
3607 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003608 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003609 break;
3610 }
3611
3612 Diag(Target->getLocation(), diag::note_using_decl_target);
3613 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3614 return true;
3615 }
3616
3617 // Target is not a function.
3618
John McCall84d87672009-12-10 09:41:52 +00003619 if (isa<TagDecl>(Target)) {
3620 // No conflict between a tag and a non-tag.
3621 if (!Tag) return false;
3622
John McCalle29c5cd2009-12-10 19:51:03 +00003623 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003624 Diag(Target->getLocation(), diag::note_using_decl_target);
3625 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3626 return true;
3627 }
3628
3629 // No conflict between a tag and a non-tag.
3630 if (!NonTag) return false;
3631
John McCalle29c5cd2009-12-10 19:51:03 +00003632 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003633 Diag(Target->getLocation(), diag::note_using_decl_target);
3634 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3635 return true;
3636}
3637
John McCall3f746822009-11-17 05:59:44 +00003638/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003639UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003640 UsingDecl *UD,
3641 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003642
3643 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003644 NamedDecl *Target = Orig;
3645 if (isa<UsingShadowDecl>(Target)) {
3646 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3647 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003648 }
3649
3650 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003651 = UsingShadowDecl::Create(Context, CurContext,
3652 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003653 UD->addShadowDecl(Shadow);
3654
3655 if (S)
John McCall3969e302009-12-08 07:46:18 +00003656 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003657 else
John McCall3969e302009-12-08 07:46:18 +00003658 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003659 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003660
John McCallda4458e2010-03-31 01:36:47 +00003661 // Register it as a conversion if appropriate.
3662 if (Shadow->getDeclName().getNameKind()
3663 == DeclarationName::CXXConversionFunctionName)
3664 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3665
John McCall3969e302009-12-08 07:46:18 +00003666 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3667 Shadow->setInvalidDecl();
3668
John McCall84d87672009-12-10 09:41:52 +00003669 return Shadow;
3670}
John McCall3969e302009-12-08 07:46:18 +00003671
John McCall84d87672009-12-10 09:41:52 +00003672/// Hides a using shadow declaration. This is required by the current
3673/// using-decl implementation when a resolvable using declaration in a
3674/// class is followed by a declaration which would hide or override
3675/// one or more of the using decl's targets; for example:
3676///
3677/// struct Base { void foo(int); };
3678/// struct Derived : Base {
3679/// using Base::foo;
3680/// void foo(int);
3681/// };
3682///
3683/// The governing language is C++03 [namespace.udecl]p12:
3684///
3685/// When a using-declaration brings names from a base class into a
3686/// derived class scope, member functions in the derived class
3687/// override and/or hide member functions with the same name and
3688/// parameter types in a base class (rather than conflicting).
3689///
3690/// There are two ways to implement this:
3691/// (1) optimistically create shadow decls when they're not hidden
3692/// by existing declarations, or
3693/// (2) don't create any shadow decls (or at least don't make them
3694/// visible) until we've fully parsed/instantiated the class.
3695/// The problem with (1) is that we might have to retroactively remove
3696/// a shadow decl, which requires several O(n) operations because the
3697/// decl structures are (very reasonably) not designed for removal.
3698/// (2) avoids this but is very fiddly and phase-dependent.
3699void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003700 if (Shadow->getDeclName().getNameKind() ==
3701 DeclarationName::CXXConversionFunctionName)
3702 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3703
John McCall84d87672009-12-10 09:41:52 +00003704 // Remove it from the DeclContext...
3705 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003706
John McCall84d87672009-12-10 09:41:52 +00003707 // ...and the scope, if applicable...
3708 if (S) {
3709 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3710 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003711 }
3712
John McCall84d87672009-12-10 09:41:52 +00003713 // ...and the using decl.
3714 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3715
3716 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003717 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003718}
3719
John McCalle61f2ba2009-11-18 02:36:19 +00003720/// Builds a using declaration.
3721///
3722/// \param IsInstantiation - Whether this call arises from an
3723/// instantiation of an unresolved using declaration. We treat
3724/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003725NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3726 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003727 CXXScopeSpec &SS,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003728 SourceLocation IdentLoc,
3729 DeclarationName Name,
3730 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003731 bool IsInstantiation,
3732 bool IsTypeName,
3733 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003734 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3735 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003736
Anders Carlssonf038fc22009-08-28 05:49:21 +00003737 // FIXME: We ignore attributes for now.
3738 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003739
Anders Carlsson59140b32009-08-28 03:16:11 +00003740 if (SS.isEmpty()) {
3741 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003742 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
John McCall84d87672009-12-10 09:41:52 +00003745 // Do the redeclaration lookup in the current scope.
3746 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3747 ForRedeclaration);
3748 Previous.setHideTags(false);
3749 if (S) {
3750 LookupName(Previous, S);
3751
3752 // It is really dumb that we have to do this.
3753 LookupResult::Filter F = Previous.makeFilter();
3754 while (F.hasNext()) {
3755 NamedDecl *D = F.next();
3756 if (!isDeclInScope(D, CurContext, S))
3757 F.erase();
3758 }
3759 F.done();
3760 } else {
3761 assert(IsInstantiation && "no scope in non-instantiation");
3762 assert(CurContext->isRecord() && "scope not record in instantiation");
3763 LookupQualifiedName(Previous, CurContext);
3764 }
3765
Mike Stump11289f42009-09-09 15:08:12 +00003766 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003767 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3768
John McCall84d87672009-12-10 09:41:52 +00003769 // Check for invalid redeclarations.
3770 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3771 return 0;
3772
3773 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003774 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3775 return 0;
3776
John McCall84c16cf2009-11-12 03:15:40 +00003777 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003778 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003779 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003780 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003781 // FIXME: not all declaration name kinds are legal here
3782 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3783 UsingLoc, TypenameLoc,
3784 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003785 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003786 } else {
3787 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3788 UsingLoc, SS.getRange(), NNS,
3789 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003790 }
John McCallb96ec562009-12-04 22:46:56 +00003791 } else {
3792 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3793 SS.getRange(), UsingLoc, NNS, Name,
3794 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003795 }
John McCallb96ec562009-12-04 22:46:56 +00003796 D->setAccess(AS);
3797 CurContext->addDecl(D);
3798
3799 if (!LookupContext) return D;
3800 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003801
John McCall0b66eb32010-05-01 00:40:08 +00003802 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003803 UD->setInvalidDecl();
3804 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003805 }
3806
John McCall3969e302009-12-08 07:46:18 +00003807 // Look up the target name.
3808
John McCall27b18f82009-11-17 02:14:36 +00003809 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003810
John McCall3969e302009-12-08 07:46:18 +00003811 // Unlike most lookups, we don't always want to hide tag
3812 // declarations: tag names are visible through the using declaration
3813 // even if hidden by ordinary names, *except* in a dependent context
3814 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003815 if (!IsInstantiation)
3816 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003817
John McCall27b18f82009-11-17 02:14:36 +00003818 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003819
John McCall9f3059a2009-10-09 21:13:30 +00003820 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003821 Diag(IdentLoc, diag::err_no_member)
3822 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003823 UD->setInvalidDecl();
3824 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003825 }
3826
John McCallb96ec562009-12-04 22:46:56 +00003827 if (R.isAmbiguous()) {
3828 UD->setInvalidDecl();
3829 return UD;
3830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
John McCalle61f2ba2009-11-18 02:36:19 +00003832 if (IsTypeName) {
3833 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003834 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003835 Diag(IdentLoc, diag::err_using_typename_non_type);
3836 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3837 Diag((*I)->getUnderlyingDecl()->getLocation(),
3838 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003839 UD->setInvalidDecl();
3840 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003841 }
3842 } else {
3843 // If we asked for a non-typename and we got a type, error out,
3844 // but only if this is an instantiation of an unresolved using
3845 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003846 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003847 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3848 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003849 UD->setInvalidDecl();
3850 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003851 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003852 }
3853
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003854 // C++0x N2914 [namespace.udecl]p6:
3855 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003856 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003857 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3858 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003859 UD->setInvalidDecl();
3860 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003861 }
Mike Stump11289f42009-09-09 15:08:12 +00003862
John McCall84d87672009-12-10 09:41:52 +00003863 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3864 if (!CheckUsingShadowDecl(UD, *I, Previous))
3865 BuildUsingShadowDecl(S, UD, *I);
3866 }
John McCall3f746822009-11-17 05:59:44 +00003867
3868 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003869}
3870
John McCall84d87672009-12-10 09:41:52 +00003871/// Checks that the given using declaration is not an invalid
3872/// redeclaration. Note that this is checking only for the using decl
3873/// itself, not for any ill-formedness among the UsingShadowDecls.
3874bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3875 bool isTypeName,
3876 const CXXScopeSpec &SS,
3877 SourceLocation NameLoc,
3878 const LookupResult &Prev) {
3879 // C++03 [namespace.udecl]p8:
3880 // C++0x [namespace.udecl]p10:
3881 // A using-declaration is a declaration and can therefore be used
3882 // repeatedly where (and only where) multiple declarations are
3883 // allowed.
3884 // That's only in file contexts.
3885 if (CurContext->getLookupContext()->isFileContext())
3886 return false;
3887
3888 NestedNameSpecifier *Qual
3889 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3890
3891 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3892 NamedDecl *D = *I;
3893
3894 bool DTypename;
3895 NestedNameSpecifier *DQual;
3896 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3897 DTypename = UD->isTypeName();
3898 DQual = UD->getTargetNestedNameDecl();
3899 } else if (UnresolvedUsingValueDecl *UD
3900 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3901 DTypename = false;
3902 DQual = UD->getTargetNestedNameSpecifier();
3903 } else if (UnresolvedUsingTypenameDecl *UD
3904 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3905 DTypename = true;
3906 DQual = UD->getTargetNestedNameSpecifier();
3907 } else continue;
3908
3909 // using decls differ if one says 'typename' and the other doesn't.
3910 // FIXME: non-dependent using decls?
3911 if (isTypeName != DTypename) continue;
3912
3913 // using decls differ if they name different scopes (but note that
3914 // template instantiation can cause this check to trigger when it
3915 // didn't before instantiation).
3916 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3917 Context.getCanonicalNestedNameSpecifier(DQual))
3918 continue;
3919
3920 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003921 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003922 return true;
3923 }
3924
3925 return false;
3926}
3927
John McCall3969e302009-12-08 07:46:18 +00003928
John McCallb96ec562009-12-04 22:46:56 +00003929/// Checks that the given nested-name qualifier used in a using decl
3930/// in the current context is appropriately related to the current
3931/// scope. If an error is found, diagnoses it and returns true.
3932bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3933 const CXXScopeSpec &SS,
3934 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003935 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003936
John McCall3969e302009-12-08 07:46:18 +00003937 if (!CurContext->isRecord()) {
3938 // C++03 [namespace.udecl]p3:
3939 // C++0x [namespace.udecl]p8:
3940 // A using-declaration for a class member shall be a member-declaration.
3941
3942 // If we weren't able to compute a valid scope, it must be a
3943 // dependent class scope.
3944 if (!NamedContext || NamedContext->isRecord()) {
3945 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3946 << SS.getRange();
3947 return true;
3948 }
3949
3950 // Otherwise, everything is known to be fine.
3951 return false;
3952 }
3953
3954 // The current scope is a record.
3955
3956 // If the named context is dependent, we can't decide much.
3957 if (!NamedContext) {
3958 // FIXME: in C++0x, we can diagnose if we can prove that the
3959 // nested-name-specifier does not refer to a base class, which is
3960 // still possible in some cases.
3961
3962 // Otherwise we have to conservatively report that things might be
3963 // okay.
3964 return false;
3965 }
3966
3967 if (!NamedContext->isRecord()) {
3968 // Ideally this would point at the last name in the specifier,
3969 // but we don't have that level of source info.
3970 Diag(SS.getRange().getBegin(),
3971 diag::err_using_decl_nested_name_specifier_is_not_class)
3972 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3973 return true;
3974 }
3975
3976 if (getLangOptions().CPlusPlus0x) {
3977 // C++0x [namespace.udecl]p3:
3978 // In a using-declaration used as a member-declaration, the
3979 // nested-name-specifier shall name a base class of the class
3980 // being defined.
3981
3982 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3983 cast<CXXRecordDecl>(NamedContext))) {
3984 if (CurContext == NamedContext) {
3985 Diag(NameLoc,
3986 diag::err_using_decl_nested_name_specifier_is_current_class)
3987 << SS.getRange();
3988 return true;
3989 }
3990
3991 Diag(SS.getRange().getBegin(),
3992 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3993 << (NestedNameSpecifier*) SS.getScopeRep()
3994 << cast<CXXRecordDecl>(CurContext)
3995 << SS.getRange();
3996 return true;
3997 }
3998
3999 return false;
4000 }
4001
4002 // C++03 [namespace.udecl]p4:
4003 // A using-declaration used as a member-declaration shall refer
4004 // to a member of a base class of the class being defined [etc.].
4005
4006 // Salient point: SS doesn't have to name a base class as long as
4007 // lookup only finds members from base classes. Therefore we can
4008 // diagnose here only if we can prove that that can't happen,
4009 // i.e. if the class hierarchies provably don't intersect.
4010
4011 // TODO: it would be nice if "definitely valid" results were cached
4012 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4013 // need to be repeated.
4014
4015 struct UserData {
4016 llvm::DenseSet<const CXXRecordDecl*> Bases;
4017
4018 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4019 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4020 Data->Bases.insert(Base);
4021 return true;
4022 }
4023
4024 bool hasDependentBases(const CXXRecordDecl *Class) {
4025 return !Class->forallBases(collect, this);
4026 }
4027
4028 /// Returns true if the base is dependent or is one of the
4029 /// accumulated base classes.
4030 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4031 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4032 return !Data->Bases.count(Base);
4033 }
4034
4035 bool mightShareBases(const CXXRecordDecl *Class) {
4036 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4037 }
4038 };
4039
4040 UserData Data;
4041
4042 // Returns false if we find a dependent base.
4043 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4044 return false;
4045
4046 // Returns false if the class has a dependent base or if it or one
4047 // of its bases is present in the base set of the current context.
4048 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4049 return false;
4050
4051 Diag(SS.getRange().getBegin(),
4052 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4053 << (NestedNameSpecifier*) SS.getScopeRep()
4054 << cast<CXXRecordDecl>(CurContext)
4055 << SS.getRange();
4056
4057 return true;
John McCallb96ec562009-12-04 22:46:56 +00004058}
4059
Mike Stump11289f42009-09-09 15:08:12 +00004060Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004061 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004062 SourceLocation AliasLoc,
4063 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004064 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004065 SourceLocation IdentLoc,
4066 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004067
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004068 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004069 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4070 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004071
Anders Carlssondca83c42009-03-28 06:23:46 +00004072 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004073 NamedDecl *PrevDecl
4074 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4075 ForRedeclaration);
4076 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4077 PrevDecl = 0;
4078
4079 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004080 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004081 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004082 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004083 // FIXME: At some point, we'll want to create the (redundant)
4084 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004085 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004086 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004087 return DeclPtrTy();
4088 }
Mike Stump11289f42009-09-09 15:08:12 +00004089
Anders Carlssondca83c42009-03-28 06:23:46 +00004090 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4091 diag::err_redefinition_different_kind;
4092 Diag(AliasLoc, DiagID) << Alias;
4093 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004094 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004095 }
4096
John McCall27b18f82009-11-17 02:14:36 +00004097 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004098 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004099
John McCall9f3059a2009-10-09 21:13:30 +00004100 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00004101 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004102 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00004103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004105 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004106 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4107 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004108 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004109 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004110
John McCalld8d0d432010-02-16 06:53:13 +00004111 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004112 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004113}
4114
Douglas Gregora57478e2010-05-01 15:04:51 +00004115namespace {
4116 /// \brief Scoped object used to handle the state changes required in Sema
4117 /// to implicitly define the body of a C++ member function;
4118 class ImplicitlyDefinedFunctionScope {
4119 Sema &S;
4120 DeclContext *PreviousContext;
4121
4122 public:
4123 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4124 : S(S), PreviousContext(S.CurContext)
4125 {
4126 S.CurContext = Method;
4127 S.PushFunctionScope();
4128 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4129 }
4130
4131 ~ImplicitlyDefinedFunctionScope() {
4132 S.PopExpressionEvaluationContext();
4133 S.PopFunctionOrBlockScope();
4134 S.CurContext = PreviousContext;
4135 }
4136 };
4137}
4138
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004139void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4140 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004141 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4142 !Constructor->isUsed()) &&
4143 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004144
Anders Carlsson423f5d82010-04-23 16:04:08 +00004145 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004146 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004147
Douglas Gregora57478e2010-05-01 15:04:51 +00004148 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004149 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004150 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004151 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004152 Constructor->setInvalidDecl();
4153 } else {
4154 Constructor->setUsed();
4155 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004156}
4157
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004158void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004159 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004160 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4161 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004162 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004163 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004164
Douglas Gregora57478e2010-05-01 15:04:51 +00004165 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004166
John McCalla6309952010-03-16 21:39:52 +00004167 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4168 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004169
Anders Carlsson26a807d2009-11-30 21:24:50 +00004170 // FIXME: If CheckDestructor fails, we should emit a note about where the
4171 // implicit destructor was needed.
4172 if (CheckDestructor(Destructor)) {
4173 Diag(CurrentLocation, diag::note_member_synthesized_at)
4174 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4175
4176 Destructor->setInvalidDecl();
4177 return;
4178 }
4179
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004180 Destructor->setUsed();
4181}
4182
Douglas Gregorb139cd52010-05-01 20:49:11 +00004183/// \brief Builds a statement that copies the given entity from \p From to
4184/// \c To.
4185///
4186/// This routine is used to copy the members of a class with an
4187/// implicitly-declared copy assignment operator. When the entities being
4188/// copied are arrays, this routine builds for loops to copy them.
4189///
4190/// \param S The Sema object used for type-checking.
4191///
4192/// \param Loc The location where the implicit copy is being generated.
4193///
4194/// \param T The type of the expressions being copied. Both expressions must
4195/// have this type.
4196///
4197/// \param To The expression we are copying to.
4198///
4199/// \param From The expression we are copying from.
4200///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004201/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4202/// Otherwise, it's a non-static member subobject.
4203///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004204/// \param Depth Internal parameter recording the depth of the recursion.
4205///
4206/// \returns A statement or a loop that copies the expressions.
4207static Sema::OwningStmtResult
4208BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4209 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004210 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004211 typedef Sema::OwningStmtResult OwningStmtResult;
4212 typedef Sema::OwningExprResult OwningExprResult;
4213
4214 // C++0x [class.copy]p30:
4215 // Each subobject is assigned in the manner appropriate to its type:
4216 //
4217 // - if the subobject is of class type, the copy assignment operator
4218 // for the class is used (as if by explicit qualification; that is,
4219 // ignoring any possible virtual overriding functions in more derived
4220 // classes);
4221 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4222 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4223
4224 // Look for operator=.
4225 DeclarationName Name
4226 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4227 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4228 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4229
4230 // Filter out any result that isn't a copy-assignment operator.
4231 LookupResult::Filter F = OpLookup.makeFilter();
4232 while (F.hasNext()) {
4233 NamedDecl *D = F.next();
4234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4235 if (Method->isCopyAssignmentOperator())
4236 continue;
4237
4238 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004239 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004240 F.done();
4241
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004242 // Suppress the protected check (C++ [class.protected]) for each of the
4243 // assignment operators we found. This strange dance is required when
4244 // we're assigning via a base classes's copy-assignment operator. To
4245 // ensure that we're getting the right base class subobject (without
4246 // ambiguities), we need to cast "this" to that subobject type; to
4247 // ensure that we don't go through the virtual call mechanism, we need
4248 // to qualify the operator= name with the base class (see below). However,
4249 // this means that if the base class has a protected copy assignment
4250 // operator, the protected member access check will fail. So, we
4251 // rewrite "protected" access to "public" access in this case, since we
4252 // know by construction that we're calling from a derived class.
4253 if (CopyingBaseSubobject) {
4254 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4255 L != LEnd; ++L) {
4256 if (L.getAccess() == AS_protected)
4257 L.setAccess(AS_public);
4258 }
4259 }
4260
Douglas Gregorb139cd52010-05-01 20:49:11 +00004261 // Create the nested-name-specifier that will be used to qualify the
4262 // reference to operator=; this is required to suppress the virtual
4263 // call mechanism.
4264 CXXScopeSpec SS;
4265 SS.setRange(Loc);
4266 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4267 T.getTypePtr()));
4268
4269 // Create the reference to operator=.
4270 OwningExprResult OpEqualRef
4271 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4272 /*FirstQualifierInScope=*/0, OpLookup,
4273 /*TemplateArgs=*/0,
4274 /*SuppressQualifierCheck=*/true);
4275 if (OpEqualRef.isInvalid())
4276 return S.StmtError();
4277
4278 // Build the call to the assignment operator.
4279 Expr *FromE = From.takeAs<Expr>();
4280 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4281 OpEqualRef.takeAs<Expr>(),
4282 Loc, &FromE, 1, 0, Loc);
4283 if (Call.isInvalid())
4284 return S.StmtError();
4285
4286 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004287 }
John McCallab8c2732010-03-16 06:11:48 +00004288
Douglas Gregorb139cd52010-05-01 20:49:11 +00004289 // - if the subobject is of scalar type, the built-in assignment
4290 // operator is used.
4291 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4292 if (!ArrayTy) {
4293 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4294 BinaryOperator::Assign,
4295 To.takeAs<Expr>(),
4296 From.takeAs<Expr>());
4297 if (Assignment.isInvalid())
4298 return S.StmtError();
4299
4300 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004301 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004302
4303 // - if the subobject is an array, each element is assigned, in the
4304 // manner appropriate to the element type;
4305
4306 // Construct a loop over the array bounds, e.g.,
4307 //
4308 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4309 //
4310 // that will copy each of the array elements.
4311 QualType SizeType = S.Context.getSizeType();
4312
4313 // Create the iteration variable.
4314 IdentifierInfo *IterationVarName = 0;
4315 {
4316 llvm::SmallString<8> Str;
4317 llvm::raw_svector_ostream OS(Str);
4318 OS << "__i" << Depth;
4319 IterationVarName = &S.Context.Idents.get(OS.str());
4320 }
4321 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4322 IterationVarName, SizeType,
4323 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4324 VarDecl::None, VarDecl::None);
4325
4326 // Initialize the iteration variable to zero.
4327 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4328 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4329
4330 // Create a reference to the iteration variable; we'll use this several
4331 // times throughout.
4332 Expr *IterationVarRef
4333 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4334 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4335
4336 // Create the DeclStmt that holds the iteration variable.
4337 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4338
4339 // Create the comparison against the array bound.
4340 llvm::APInt Upper = ArrayTy->getSize();
4341 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4342 OwningExprResult Comparison
4343 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4344 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4345 BinaryOperator::NE, S.Context.BoolTy, Loc));
4346
4347 // Create the pre-increment of the iteration variable.
4348 OwningExprResult Increment
4349 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4350 UnaryOperator::PreInc,
4351 SizeType, Loc));
4352
4353 // Subscript the "from" and "to" expressions with the iteration variable.
4354 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4355 S.Owned(IterationVarRef->Retain()),
4356 Loc);
4357 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4358 S.Owned(IterationVarRef->Retain()),
4359 Loc);
4360 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4361 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4362
4363 // Build the copy for an individual element of the array.
4364 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4365 ArrayTy->getElementType(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004366 move(To), move(From),
4367 CopyingBaseSubobject, Depth+1);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004368 if (Copy.isInvalid()) {
4369 InitStmt->Destroy(S.Context);
4370 return S.StmtError();
4371 }
4372
4373 // Construct the loop that copies all elements of this array.
4374 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4375 S.MakeFullExpr(Comparison),
4376 Sema::DeclPtrTy(),
4377 S.MakeFullExpr(Increment),
4378 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004379}
4380
Douglas Gregorb139cd52010-05-01 20:49:11 +00004381void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4382 CXXMethodDecl *CopyAssignOperator) {
4383 assert((CopyAssignOperator->isImplicit() &&
4384 CopyAssignOperator->isOverloadedOperator() &&
4385 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4386 !CopyAssignOperator->isUsed()) &&
4387 "DefineImplicitCopyAssignment called for wrong function");
4388
4389 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4390
4391 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4392 CopyAssignOperator->setInvalidDecl();
4393 return;
4394 }
4395
4396 CopyAssignOperator->setUsed();
4397
4398 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
4399
4400 // C++0x [class.copy]p30:
4401 // The implicitly-defined or explicitly-defaulted copy assignment operator
4402 // for a non-union class X performs memberwise copy assignment of its
4403 // subobjects. The direct base classes of X are assigned first, in the
4404 // order of their declaration in the base-specifier-list, and then the
4405 // immediate non-static data members of X are assigned, in the order in
4406 // which they were declared in the class definition.
4407
4408 // The statements that form the synthesized function body.
4409 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4410
4411 // The parameter for the "other" object, which we are copying from.
4412 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4413 Qualifiers OtherQuals = Other->getType().getQualifiers();
4414 QualType OtherRefType = Other->getType();
4415 if (const LValueReferenceType *OtherRef
4416 = OtherRefType->getAs<LValueReferenceType>()) {
4417 OtherRefType = OtherRef->getPointeeType();
4418 OtherQuals = OtherRefType.getQualifiers();
4419 }
4420
4421 // Our location for everything implicitly-generated.
4422 SourceLocation Loc = CopyAssignOperator->getLocation();
4423
4424 // Construct a reference to the "other" object. We'll be using this
4425 // throughout the generated ASTs.
4426 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4427 assert(OtherRef && "Reference to parameter cannot fail!");
4428
4429 // Construct the "this" pointer. We'll be using this throughout the generated
4430 // ASTs.
4431 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4432 assert(This && "Reference to this cannot fail!");
4433
4434 // Assign base classes.
4435 bool Invalid = false;
4436 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4437 E = ClassDecl->bases_end(); Base != E; ++Base) {
4438 // Form the assignment:
4439 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4440 QualType BaseType = Base->getType().getUnqualifiedType();
4441 CXXRecordDecl *BaseClassDecl = 0;
4442 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4443 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4444 else {
4445 Invalid = true;
4446 continue;
4447 }
4448
4449 // Construct the "from" expression, which is an implicit cast to the
4450 // appropriately-qualified base type.
4451 Expr *From = OtherRef->Retain();
4452 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4453 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4454 CXXBaseSpecifierArray(Base));
4455
4456 // Dereference "this".
4457 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4458 Owned(This->Retain()));
4459
4460 // Implicitly cast "this" to the appropriately-qualified base type.
4461 Expr *ToE = To.takeAs<Expr>();
4462 ImpCastExprToType(ToE,
4463 Context.getCVRQualifiedType(BaseType,
4464 CopyAssignOperator->getTypeQualifiers()),
4465 CastExpr::CK_UncheckedDerivedToBase,
4466 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4467 To = Owned(ToE);
4468
4469 // Build the copy.
4470 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004471 move(To), Owned(From),
4472 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004473 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004474 Diag(CurrentLocation, diag::note_member_synthesized_at)
4475 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4476 CopyAssignOperator->setInvalidDecl();
4477 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004478 }
4479
4480 // Success! Record the copy.
4481 Statements.push_back(Copy.takeAs<Expr>());
4482 }
4483
4484 // \brief Reference to the __builtin_memcpy function.
4485 Expr *BuiltinMemCpyRef = 0;
4486
4487 // Assign non-static members.
4488 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4489 FieldEnd = ClassDecl->field_end();
4490 Field != FieldEnd; ++Field) {
4491 // Check for members of reference type; we can't copy those.
4492 if (Field->getType()->isReferenceType()) {
4493 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4494 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4495 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004496 Diag(CurrentLocation, diag::note_member_synthesized_at)
4497 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004498 Invalid = true;
4499 continue;
4500 }
4501
4502 // Check for members of const-qualified, non-class type.
4503 QualType BaseType = Context.getBaseElementType(Field->getType());
4504 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4505 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4506 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4507 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004508 Diag(CurrentLocation, diag::note_member_synthesized_at)
4509 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004510 Invalid = true;
4511 continue;
4512 }
4513
4514 QualType FieldType = Field->getType().getNonReferenceType();
4515
4516 // Build references to the field in the object we're copying from and to.
4517 CXXScopeSpec SS; // Intentionally empty
4518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4519 LookupMemberName);
4520 MemberLookup.addDecl(*Field);
4521 MemberLookup.resolveKind();
4522 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4523 OtherRefType,
4524 Loc, /*IsArrow=*/false,
4525 SS, 0, MemberLookup, 0);
4526 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4527 This->getType(),
4528 Loc, /*IsArrow=*/true,
4529 SS, 0, MemberLookup, 0);
4530 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4531 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4532
4533 // If the field should be copied with __builtin_memcpy rather than via
4534 // explicit assignments, do so. This optimization only applies for arrays
4535 // of scalars and arrays of class type with trivial copy-assignment
4536 // operators.
4537 if (FieldType->isArrayType() &&
4538 (!BaseType->isRecordType() ||
4539 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4540 ->hasTrivialCopyAssignment())) {
4541 // Compute the size of the memory buffer to be copied.
4542 QualType SizeType = Context.getSizeType();
4543 llvm::APInt Size(Context.getTypeSize(SizeType),
4544 Context.getTypeSizeInChars(BaseType).getQuantity());
4545 for (const ConstantArrayType *Array
4546 = Context.getAsConstantArrayType(FieldType);
4547 Array;
4548 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4549 llvm::APInt ArraySize = Array->getSize();
4550 ArraySize.zextOrTrunc(Size.getBitWidth());
4551 Size *= ArraySize;
4552 }
4553
4554 // Take the address of the field references for "from" and "to".
4555 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4556 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4557
4558 // Create a reference to the __builtin_memcpy builtin function.
4559 if (!BuiltinMemCpyRef) {
4560 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4561 LookupOrdinaryName);
4562 LookupName(R, TUScope, true);
4563
4564 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4565 if (!BuiltinMemCpy) {
4566 // Something went horribly wrong earlier, and we will have complained
4567 // about it.
4568 Invalid = true;
4569 continue;
4570 }
4571
4572 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4573 BuiltinMemCpy->getType(),
4574 Loc, 0).takeAs<Expr>();
4575 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4576 }
4577
4578 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4579 CallArgs.push_back(To.takeAs<Expr>());
4580 CallArgs.push_back(From.takeAs<Expr>());
4581 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4582 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4583 Commas.push_back(Loc);
4584 Commas.push_back(Loc);
4585 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4586 Owned(BuiltinMemCpyRef->Retain()),
4587 Loc, move_arg(CallArgs),
4588 Commas.data(), Loc);
4589 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4590 Statements.push_back(Call.takeAs<Expr>());
4591 continue;
4592 }
4593
4594 // Build the copy of this field.
4595 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004596 move(To), move(From),
4597 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004598 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004599 Diag(CurrentLocation, diag::note_member_synthesized_at)
4600 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4601 CopyAssignOperator->setInvalidDecl();
4602 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004603 }
4604
4605 // Success! Record the copy.
4606 Statements.push_back(Copy.takeAs<Stmt>());
4607 }
4608
4609 if (!Invalid) {
4610 // Add a "return *this;"
4611 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4612 Owned(This->Retain()));
4613
4614 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4615 if (Return.isInvalid())
4616 Invalid = true;
4617 else {
4618 Statements.push_back(Return.takeAs<Stmt>());
4619 }
4620 }
4621
4622 if (Invalid) {
4623 CopyAssignOperator->setInvalidDecl();
4624 return;
4625 }
4626
4627 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4628 /*isStmtExpr=*/false);
4629 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4630 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004631}
4632
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004633void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4634 CXXConstructorDecl *CopyConstructor,
4635 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00004636 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00004637 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004638 !CopyConstructor->isUsed()) &&
4639 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004640
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00004641 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004642 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004643
Douglas Gregora57478e2010-05-01 15:04:51 +00004644 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004645
Anders Carlsson79111502010-05-01 16:39:01 +00004646 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4647 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00004648 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00004649 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00004650 } else {
4651 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
4652 CopyConstructor->getLocation(),
4653 MultiStmtArg(*this, 0, 0),
4654 /*isStmtExpr=*/false)
4655 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00004656 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00004657
4658 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004659}
4660
Anders Carlsson6eb55572009-08-25 05:12:04 +00004661Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004662Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00004663 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004664 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004665 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004666 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00004667 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00004668
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004669 // C++0x [class.copy]p34:
4670 // When certain criteria are met, an implementation is allowed to
4671 // omit the copy/move construction of a class object, even if the
4672 // copy/move constructor and/or destructor for the object have
4673 // side effects. [...]
4674 // - when a temporary class object that has not been bound to a
4675 // reference (12.2) would be copied/moved to a class object
4676 // with the same cv-unqualified type, the copy/move operation
4677 // can be omitted by constructing the temporary object
4678 // directly into the target of the omitted copy/move
4679 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4680 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4681 Elidable = SubExpr->isTemporaryObject() &&
4682 Context.hasSameUnqualifiedType(SubExpr->getType(),
4683 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00004684 }
Mike Stump11289f42009-09-09 15:08:12 +00004685
4686 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004687 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004688 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00004689}
4690
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004691/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4692/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004693Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004694Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4695 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004696 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004697 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004698 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004699 unsigned NumExprs = ExprArgs.size();
4700 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004701
Douglas Gregor27381f32009-11-23 12:27:39 +00004702 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004703 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004704 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004705 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004706}
4707
Mike Stump11289f42009-09-09 15:08:12 +00004708bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004709 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004710 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004711 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004712 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004713 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004714 if (TempResult.isInvalid())
4715 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Anders Carlsson6eb55572009-08-25 05:12:04 +00004717 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004718 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004719 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004720 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004721
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004722 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004723}
4724
John McCall03c48482010-02-02 09:10:11 +00004725void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4726 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004727 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4728 !ClassDecl->hasTrivialDestructor()) {
John McCall6781b052010-02-02 08:45:54 +00004729 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4730 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00004731 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00004732 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00004733 << VD->getDeclName()
4734 << VD->getType());
John McCall6781b052010-02-02 08:45:54 +00004735 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004736}
4737
Mike Stump11289f42009-09-09 15:08:12 +00004738/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004739/// ActOnDeclarator, when a C++ direct initializer is present.
4740/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004741void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4742 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004743 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004744 SourceLocation *CommaLocs,
4745 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004746 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004747 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004748
4749 // If there is no declaration, there was an error parsing it. Just ignore
4750 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004751 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004752 return;
Mike Stump11289f42009-09-09 15:08:12 +00004753
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004754 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4755 if (!VDecl) {
4756 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4757 RealDecl->setInvalidDecl();
4758 return;
4759 }
4760
Douglas Gregor402250f2009-08-26 21:14:46 +00004761 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004762 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004763 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4764 //
4765 // Clients that want to distinguish between the two forms, can check for
4766 // direct initializer using VarDecl::hasCXXDirectInitializer().
4767 // A major benefit is that clients that don't particularly care about which
4768 // exactly form was it (like the CodeGen) can handle both cases without
4769 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004770
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004771 // C++ 8.5p11:
4772 // The form of initialization (using parentheses or '=') is generally
4773 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004774 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004775 QualType DeclInitType = VDecl->getType();
4776 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004777 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004778
Douglas Gregor50dc2192010-02-11 22:55:30 +00004779 if (!VDecl->getType()->isDependentType() &&
4780 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004781 diag::err_typecheck_decl_incomplete_type)) {
4782 VDecl->setInvalidDecl();
4783 return;
4784 }
4785
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004786 // The variable can not have an abstract class type.
4787 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4788 diag::err_abstract_type_in_decl,
4789 AbstractVariableType))
4790 VDecl->setInvalidDecl();
4791
Sebastian Redl5ca79842010-02-01 20:16:42 +00004792 const VarDecl *Def;
4793 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004794 Diag(VDecl->getLocation(), diag::err_redefinition)
4795 << VDecl->getDeclName();
4796 Diag(Def->getLocation(), diag::note_previous_definition);
4797 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004798 return;
4799 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004800
4801 // If either the declaration has a dependent type or if any of the
4802 // expressions is type-dependent, we represent the initialization
4803 // via a ParenListExpr for later use during template instantiation.
4804 if (VDecl->getType()->isDependentType() ||
4805 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4806 // Let clients know that initialization was done with a direct initializer.
4807 VDecl->setCXXDirectInitializer(true);
4808
4809 // Store the initialization expressions as a ParenListExpr.
4810 unsigned NumExprs = Exprs.size();
4811 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4812 (Expr **)Exprs.release(),
4813 NumExprs, RParenLoc));
4814 return;
4815 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004816
4817 // Capture the variable that is being initialized and the style of
4818 // initialization.
4819 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4820
4821 // FIXME: Poor source location information.
4822 InitializationKind Kind
4823 = InitializationKind::CreateDirect(VDecl->getLocation(),
4824 LParenLoc, RParenLoc);
4825
4826 InitializationSequence InitSeq(*this, Entity, Kind,
4827 (Expr**)Exprs.get(), Exprs.size());
4828 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4829 if (Result.isInvalid()) {
4830 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004831 return;
4832 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004833
4834 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004835 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004836 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004837
John McCall03c48482010-02-02 09:10:11 +00004838 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4839 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004840}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004841
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004842/// \brief Given a constructor and the set of arguments provided for the
4843/// constructor, convert the arguments and add any required default arguments
4844/// to form a proper call to this constructor.
4845///
4846/// \returns true if an error occurred, false otherwise.
4847bool
4848Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4849 MultiExprArg ArgsPtr,
4850 SourceLocation Loc,
4851 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4852 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4853 unsigned NumArgs = ArgsPtr.size();
4854 Expr **Args = (Expr **)ArgsPtr.get();
4855
4856 const FunctionProtoType *Proto
4857 = Constructor->getType()->getAs<FunctionProtoType>();
4858 assert(Proto && "Constructor without a prototype?");
4859 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004860
4861 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004862 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004863 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004864 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004865 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004866
4867 VariadicCallType CallType =
4868 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4869 llvm::SmallVector<Expr *, 8> AllArgs;
4870 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4871 Proto, 0, Args, NumArgs, AllArgs,
4872 CallType);
4873 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4874 ConvertedArgs.push_back(AllArgs[i]);
4875 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004876}
4877
Anders Carlssone363c8e2009-12-12 00:32:00 +00004878static inline bool
4879CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4880 const FunctionDecl *FnDecl) {
4881 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4882 if (isa<NamespaceDecl>(DC)) {
4883 return SemaRef.Diag(FnDecl->getLocation(),
4884 diag::err_operator_new_delete_declared_in_namespace)
4885 << FnDecl->getDeclName();
4886 }
4887
4888 if (isa<TranslationUnitDecl>(DC) &&
4889 FnDecl->getStorageClass() == FunctionDecl::Static) {
4890 return SemaRef.Diag(FnDecl->getLocation(),
4891 diag::err_operator_new_delete_declared_static)
4892 << FnDecl->getDeclName();
4893 }
4894
Anders Carlsson60659a82009-12-12 02:43:16 +00004895 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004896}
4897
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004898static inline bool
4899CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4900 CanQualType ExpectedResultType,
4901 CanQualType ExpectedFirstParamType,
4902 unsigned DependentParamTypeDiag,
4903 unsigned InvalidParamTypeDiag) {
4904 QualType ResultType =
4905 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4906
4907 // Check that the result type is not dependent.
4908 if (ResultType->isDependentType())
4909 return SemaRef.Diag(FnDecl->getLocation(),
4910 diag::err_operator_new_delete_dependent_result_type)
4911 << FnDecl->getDeclName() << ExpectedResultType;
4912
4913 // Check that the result type is what we expect.
4914 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4915 return SemaRef.Diag(FnDecl->getLocation(),
4916 diag::err_operator_new_delete_invalid_result_type)
4917 << FnDecl->getDeclName() << ExpectedResultType;
4918
4919 // A function template must have at least 2 parameters.
4920 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4921 return SemaRef.Diag(FnDecl->getLocation(),
4922 diag::err_operator_new_delete_template_too_few_parameters)
4923 << FnDecl->getDeclName();
4924
4925 // The function decl must have at least 1 parameter.
4926 if (FnDecl->getNumParams() == 0)
4927 return SemaRef.Diag(FnDecl->getLocation(),
4928 diag::err_operator_new_delete_too_few_parameters)
4929 << FnDecl->getDeclName();
4930
4931 // Check the the first parameter type is not dependent.
4932 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4933 if (FirstParamType->isDependentType())
4934 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4935 << FnDecl->getDeclName() << ExpectedFirstParamType;
4936
4937 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004938 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004939 ExpectedFirstParamType)
4940 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4941 << FnDecl->getDeclName() << ExpectedFirstParamType;
4942
4943 return false;
4944}
4945
Anders Carlsson12308f42009-12-11 23:23:22 +00004946static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004947CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004948 // C++ [basic.stc.dynamic.allocation]p1:
4949 // A program is ill-formed if an allocation function is declared in a
4950 // namespace scope other than global scope or declared static in global
4951 // scope.
4952 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4953 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004954
4955 CanQualType SizeTy =
4956 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4957
4958 // C++ [basic.stc.dynamic.allocation]p1:
4959 // The return type shall be void*. The first parameter shall have type
4960 // std::size_t.
4961 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4962 SizeTy,
4963 diag::err_operator_new_dependent_param_type,
4964 diag::err_operator_new_param_type))
4965 return true;
4966
4967 // C++ [basic.stc.dynamic.allocation]p1:
4968 // The first parameter shall not have an associated default argument.
4969 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004970 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004971 diag::err_operator_new_default_arg)
4972 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4973
4974 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004975}
4976
4977static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004978CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4979 // C++ [basic.stc.dynamic.deallocation]p1:
4980 // A program is ill-formed if deallocation functions are declared in a
4981 // namespace scope other than global scope or declared static in global
4982 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004983 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4984 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004985
4986 // C++ [basic.stc.dynamic.deallocation]p2:
4987 // Each deallocation function shall return void and its first parameter
4988 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004989 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4990 SemaRef.Context.VoidPtrTy,
4991 diag::err_operator_delete_dependent_param_type,
4992 diag::err_operator_delete_param_type))
4993 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004994
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004995 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4996 if (FirstParamType->isDependentType())
4997 return SemaRef.Diag(FnDecl->getLocation(),
4998 diag::err_operator_delete_dependent_param_type)
4999 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5000
5001 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
5002 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00005003 return SemaRef.Diag(FnDecl->getLocation(),
5004 diag::err_operator_delete_param_type)
5005 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00005006
5007 return false;
5008}
5009
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005010/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5011/// of this overloaded operator is well-formed. If so, returns false;
5012/// otherwise, emits appropriate diagnostics and returns true.
5013bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005014 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005015 "Expected an overloaded operator declaration");
5016
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005017 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5018
Mike Stump11289f42009-09-09 15:08:12 +00005019 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005020 // The allocation and deallocation functions, operator new,
5021 // operator new[], operator delete and operator delete[], are
5022 // described completely in 3.7.3. The attributes and restrictions
5023 // found in the rest of this subclause do not apply to them unless
5024 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005025 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005026 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005027
Anders Carlsson22f443f2009-12-12 00:26:23 +00005028 if (Op == OO_New || Op == OO_Array_New)
5029 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005030
5031 // C++ [over.oper]p6:
5032 // An operator function shall either be a non-static member
5033 // function or be a non-member function and have at least one
5034 // parameter whose type is a class, a reference to a class, an
5035 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005036 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5037 if (MethodDecl->isStatic())
5038 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005039 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005040 } else {
5041 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005042 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5043 ParamEnd = FnDecl->param_end();
5044 Param != ParamEnd; ++Param) {
5045 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005046 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5047 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005048 ClassOrEnumParam = true;
5049 break;
5050 }
5051 }
5052
Douglas Gregord69246b2008-11-17 16:14:12 +00005053 if (!ClassOrEnumParam)
5054 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005055 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005056 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005057 }
5058
5059 // C++ [over.oper]p8:
5060 // An operator function cannot have default arguments (8.3.6),
5061 // except where explicitly stated below.
5062 //
Mike Stump11289f42009-09-09 15:08:12 +00005063 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005064 // (C++ [over.call]p1).
5065 if (Op != OO_Call) {
5066 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5067 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005068 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005069 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005070 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005071 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005072 }
5073 }
5074
Douglas Gregor6cf08062008-11-10 13:38:07 +00005075 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5076 { false, false, false }
5077#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5078 , { Unary, Binary, MemberOnly }
5079#include "clang/Basic/OperatorKinds.def"
5080 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005081
Douglas Gregor6cf08062008-11-10 13:38:07 +00005082 bool CanBeUnaryOperator = OperatorUses[Op][0];
5083 bool CanBeBinaryOperator = OperatorUses[Op][1];
5084 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005085
5086 // C++ [over.oper]p8:
5087 // [...] Operator functions cannot have more or fewer parameters
5088 // than the number required for the corresponding operator, as
5089 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005090 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005091 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005092 if (Op != OO_Call &&
5093 ((NumParams == 1 && !CanBeUnaryOperator) ||
5094 (NumParams == 2 && !CanBeBinaryOperator) ||
5095 (NumParams < 1) || (NumParams > 2))) {
5096 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005097 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005098 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005099 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005100 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005101 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005102 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005103 assert(CanBeBinaryOperator &&
5104 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005105 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005106 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005107
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005108 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005109 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005110 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005111
Douglas Gregord69246b2008-11-17 16:14:12 +00005112 // Overloaded operators other than operator() cannot be variadic.
5113 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005114 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005115 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005116 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005117 }
5118
5119 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005120 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5121 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005122 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005123 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005124 }
5125
5126 // C++ [over.inc]p1:
5127 // The user-defined function called operator++ implements the
5128 // prefix and postfix ++ operator. If this function is a member
5129 // function with no parameters, or a non-member function with one
5130 // parameter of class or enumeration type, it defines the prefix
5131 // increment operator ++ for objects of that type. If the function
5132 // is a member function with one parameter (which shall be of type
5133 // int) or a non-member function with two parameters (the second
5134 // of which shall be of type int), it defines the postfix
5135 // increment operator ++ for objects of that type.
5136 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5137 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5138 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005139 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005140 ParamIsInt = BT->getKind() == BuiltinType::Int;
5141
Chris Lattner2b786902008-11-21 07:50:02 +00005142 if (!ParamIsInt)
5143 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005144 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005145 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005146 }
5147
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005148 // Notify the class if it got an assignment operator.
5149 if (Op == OO_Equal) {
5150 // Would have returned earlier otherwise.
5151 assert(isa<CXXMethodDecl>(FnDecl) &&
5152 "Overloaded = not member, but not filtered.");
5153 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5154 Method->getParent()->addedAssignmentOperator(Context, Method);
5155 }
5156
Douglas Gregord69246b2008-11-17 16:14:12 +00005157 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005158}
Chris Lattner3b024a32008-12-17 07:09:26 +00005159
Alexis Huntc88db062010-01-13 09:01:02 +00005160/// CheckLiteralOperatorDeclaration - Check whether the declaration
5161/// of this literal operator function is well-formed. If so, returns
5162/// false; otherwise, emits appropriate diagnostics and returns true.
5163bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5164 DeclContext *DC = FnDecl->getDeclContext();
5165 Decl::Kind Kind = DC->getDeclKind();
5166 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5167 Kind != Decl::LinkageSpec) {
5168 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5169 << FnDecl->getDeclName();
5170 return true;
5171 }
5172
5173 bool Valid = false;
5174
Alexis Hunt7dd26172010-04-07 23:11:06 +00005175 // template <char...> type operator "" name() is the only valid template
5176 // signature, and the only valid signature with no parameters.
5177 if (FnDecl->param_size() == 0) {
5178 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5179 // Must have only one template parameter
5180 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5181 if (Params->size() == 1) {
5182 NonTypeTemplateParmDecl *PmDecl =
5183 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005184
Alexis Hunt7dd26172010-04-07 23:11:06 +00005185 // The template parameter must be a char parameter pack.
5186 // FIXME: This test will always fail because non-type parameter packs
5187 // have not been implemented.
5188 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5189 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5190 Valid = true;
5191 }
5192 }
5193 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005194 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005195 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5196
Alexis Huntc88db062010-01-13 09:01:02 +00005197 QualType T = (*Param)->getType();
5198
Alexis Hunt079a6f72010-04-07 22:57:35 +00005199 // unsigned long long int, long double, and any character type are allowed
5200 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005201 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5202 Context.hasSameType(T, Context.LongDoubleTy) ||
5203 Context.hasSameType(T, Context.CharTy) ||
5204 Context.hasSameType(T, Context.WCharTy) ||
5205 Context.hasSameType(T, Context.Char16Ty) ||
5206 Context.hasSameType(T, Context.Char32Ty)) {
5207 if (++Param == FnDecl->param_end())
5208 Valid = true;
5209 goto FinishedParams;
5210 }
5211
Alexis Hunt079a6f72010-04-07 22:57:35 +00005212 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005213 const PointerType *PT = T->getAs<PointerType>();
5214 if (!PT)
5215 goto FinishedParams;
5216 T = PT->getPointeeType();
5217 if (!T.isConstQualified())
5218 goto FinishedParams;
5219 T = T.getUnqualifiedType();
5220
5221 // Move on to the second parameter;
5222 ++Param;
5223
5224 // If there is no second parameter, the first must be a const char *
5225 if (Param == FnDecl->param_end()) {
5226 if (Context.hasSameType(T, Context.CharTy))
5227 Valid = true;
5228 goto FinishedParams;
5229 }
5230
5231 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5232 // are allowed as the first parameter to a two-parameter function
5233 if (!(Context.hasSameType(T, Context.CharTy) ||
5234 Context.hasSameType(T, Context.WCharTy) ||
5235 Context.hasSameType(T, Context.Char16Ty) ||
5236 Context.hasSameType(T, Context.Char32Ty)))
5237 goto FinishedParams;
5238
5239 // The second and final parameter must be an std::size_t
5240 T = (*Param)->getType().getUnqualifiedType();
5241 if (Context.hasSameType(T, Context.getSizeType()) &&
5242 ++Param == FnDecl->param_end())
5243 Valid = true;
5244 }
5245
5246 // FIXME: This diagnostic is absolutely terrible.
5247FinishedParams:
5248 if (!Valid) {
5249 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5250 << FnDecl->getDeclName();
5251 return true;
5252 }
5253
5254 return false;
5255}
5256
Douglas Gregor07665a62009-01-05 19:45:36 +00005257/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5258/// linkage specification, including the language and (if present)
5259/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5260/// the location of the language string literal, which is provided
5261/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5262/// the '{' brace. Otherwise, this linkage specification does not
5263/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005264Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5265 SourceLocation ExternLoc,
5266 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005267 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005268 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005269 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005270 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005271 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005272 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005273 Language = LinkageSpecDecl::lang_cxx;
5274 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005275 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005276 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005277 }
Mike Stump11289f42009-09-09 15:08:12 +00005278
Chris Lattner438e5012008-12-17 07:13:27 +00005279 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005280
Douglas Gregor07665a62009-01-05 19:45:36 +00005281 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005282 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005283 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005284 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005285 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005286 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005287}
5288
Douglas Gregor07665a62009-01-05 19:45:36 +00005289/// ActOnFinishLinkageSpecification - Completely the definition of
5290/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5291/// valid, it's the position of the closing '}' brace in a linkage
5292/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005293Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5294 DeclPtrTy LinkageSpec,
5295 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005296 if (LinkageSpec)
5297 PopDeclContext();
5298 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005299}
5300
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005301/// \brief Perform semantic analysis for the variable declaration that
5302/// occurs within a C++ catch clause, returning the newly-created
5303/// variable.
5304VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005305 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005306 IdentifierInfo *Name,
5307 SourceLocation Loc,
5308 SourceRange Range) {
5309 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005310
5311 // Arrays and functions decay.
5312 if (ExDeclType->isArrayType())
5313 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5314 else if (ExDeclType->isFunctionType())
5315 ExDeclType = Context.getPointerType(ExDeclType);
5316
5317 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5318 // The exception-declaration shall not denote a pointer or reference to an
5319 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005320 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005321 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005322 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005323 Invalid = true;
5324 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005325
Douglas Gregor104ee002010-03-08 01:47:36 +00005326 // GCC allows catching pointers and references to incomplete types
5327 // as an extension; so do we, but we warn by default.
5328
Sebastian Redl54c04d42008-12-22 19:15:10 +00005329 QualType BaseType = ExDeclType;
5330 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005331 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005332 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005333 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005334 BaseType = Ptr->getPointeeType();
5335 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005336 DK = diag::ext_catch_incomplete_ptr;
5337 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005338 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005339 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005340 BaseType = Ref->getPointeeType();
5341 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005342 DK = diag::ext_catch_incomplete_ref;
5343 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005344 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005345 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005346 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5347 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005348 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005349
Mike Stump11289f42009-09-09 15:08:12 +00005350 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005351 RequireNonAbstractType(Loc, ExDeclType,
5352 diag::err_abstract_type_in_decl,
5353 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005354 Invalid = true;
5355
Mike Stump11289f42009-09-09 15:08:12 +00005356 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005357 Name, ExDeclType, TInfo, VarDecl::None,
5358 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00005359 ExDecl->setExceptionVariable(true);
5360
Douglas Gregor6de584c2010-03-05 23:38:39 +00005361 if (!Invalid) {
5362 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5363 // C++ [except.handle]p16:
5364 // The object declared in an exception-declaration or, if the
5365 // exception-declaration does not specify a name, a temporary (12.2) is
5366 // copy-initialized (8.5) from the exception object. [...]
5367 // The object is destroyed when the handler exits, after the destruction
5368 // of any automatic objects initialized within the handler.
5369 //
5370 // We just pretend to initialize the object with itself, then make sure
5371 // it can be destroyed later.
5372 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5373 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5374 Loc, ExDeclType, 0);
5375 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5376 SourceLocation());
5377 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5378 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5379 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5380 if (Result.isInvalid())
5381 Invalid = true;
5382 else
5383 FinalizeVarWithDestructor(ExDecl, RecordTy);
5384 }
5385 }
5386
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005387 if (Invalid)
5388 ExDecl->setInvalidDecl();
5389
5390 return ExDecl;
5391}
5392
5393/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5394/// handler.
5395Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005396 TypeSourceInfo *TInfo = 0;
5397 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005398
5399 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005400 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005401 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00005402 LookupOrdinaryName,
5403 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005404 // The scope should be freshly made just for us. There is just no way
5405 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005406 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005407 if (PrevDecl->isTemplateParameter()) {
5408 // Maybe we will complain about the shadowed template parameter.
5409 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005410 }
5411 }
5412
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005413 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005414 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5415 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005416 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005417 }
5418
John McCallbcd03502009-12-07 02:54:59 +00005419 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005420 D.getIdentifier(),
5421 D.getIdentifierLoc(),
5422 D.getDeclSpec().getSourceRange());
5423
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005424 if (Invalid)
5425 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005426
Sebastian Redl54c04d42008-12-22 19:15:10 +00005427 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005428 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005429 PushOnScopeChains(ExDecl, S);
5430 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005431 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005432
Douglas Gregor758a8692009-06-17 21:51:59 +00005433 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005434 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005435}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005436
Mike Stump11289f42009-09-09 15:08:12 +00005437Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005438 ExprArg assertexpr,
5439 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005440 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005441 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005442 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5443
Anders Carlsson54b26982009-03-14 00:33:21 +00005444 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5445 llvm::APSInt Value(32);
5446 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5447 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5448 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005449 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005450 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005451
Anders Carlsson54b26982009-03-14 00:33:21 +00005452 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005453 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005454 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005455 }
5456 }
Mike Stump11289f42009-09-09 15:08:12 +00005457
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005458 assertexpr.release();
5459 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005460 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005461 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005462
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005463 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005464 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005465}
Sebastian Redlf769df52009-03-24 22:27:57 +00005466
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005467/// \brief Perform semantic analysis of the given friend type declaration.
5468///
5469/// \returns A friend declaration that.
5470FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5471 TypeSourceInfo *TSInfo) {
5472 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5473
5474 QualType T = TSInfo->getType();
5475 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5476
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005477 if (!getLangOptions().CPlusPlus0x) {
5478 // C++03 [class.friend]p2:
5479 // An elaborated-type-specifier shall be used in a friend declaration
5480 // for a class.*
5481 //
5482 // * The class-key of the elaborated-type-specifier is required.
5483 if (!ActiveTemplateInstantiations.empty()) {
5484 // Do not complain about the form of friend template types during
5485 // template instantiation; we will already have complained when the
5486 // template was declared.
5487 } else if (!T->isElaboratedTypeSpecifier()) {
5488 // If we evaluated the type to a record type, suggest putting
5489 // a tag in front.
5490 if (const RecordType *RT = T->getAs<RecordType>()) {
5491 RecordDecl *RD = RT->getDecl();
5492
5493 std::string InsertionText = std::string(" ") + RD->getKindName();
5494
5495 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5496 << (unsigned) RD->getTagKind()
5497 << T
5498 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5499 InsertionText);
5500 } else {
5501 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5502 << T
5503 << SourceRange(FriendLoc, TypeRange.getEnd());
5504 }
5505 } else if (T->getAs<EnumType>()) {
5506 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005507 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005508 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005509 }
5510 }
5511
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005512 // C++0x [class.friend]p3:
5513 // If the type specifier in a friend declaration designates a (possibly
5514 // cv-qualified) class type, that class is declared as a friend; otherwise,
5515 // the friend declaration is ignored.
5516
5517 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5518 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005519
5520 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5521}
5522
John McCall11083da2009-09-16 22:47:08 +00005523/// Handle a friend type declaration. This works in tandem with
5524/// ActOnTag.
5525///
5526/// Notes on friend class templates:
5527///
5528/// We generally treat friend class declarations as if they were
5529/// declaring a class. So, for example, the elaborated type specifier
5530/// in a friend declaration is required to obey the restrictions of a
5531/// class-head (i.e. no typedefs in the scope chain), template
5532/// parameters are required to match up with simple template-ids, &c.
5533/// However, unlike when declaring a template specialization, it's
5534/// okay to refer to a template specialization without an empty
5535/// template parameter declaration, e.g.
5536/// friend class A<T>::B<unsigned>;
5537/// We permit this as a special case; if there are any template
5538/// parameters present at all, require proper matching, i.e.
5539/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005540Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005541 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005542 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005543
5544 assert(DS.isFriendSpecified());
5545 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5546
John McCall11083da2009-09-16 22:47:08 +00005547 // Try to convert the decl specifier to a type. This works for
5548 // friend templates because ActOnTag never produces a ClassTemplateDecl
5549 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005550 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall15ad0962010-03-25 18:04:51 +00005551 TypeSourceInfo *TSI;
5552 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005553 if (TheDeclarator.isInvalidType())
5554 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005555
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005556 if (!TSI)
5557 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5558
John McCall11083da2009-09-16 22:47:08 +00005559 // This is definitely an error in C++98. It's probably meant to
5560 // be forbidden in C++0x, too, but the specification is just
5561 // poorly written.
5562 //
5563 // The problem is with declarations like the following:
5564 // template <T> friend A<T>::foo;
5565 // where deciding whether a class C is a friend or not now hinges
5566 // on whether there exists an instantiation of A that causes
5567 // 'foo' to equal C. There are restrictions on class-heads
5568 // (which we declare (by fiat) elaborated friend declarations to
5569 // be) that makes this tractable.
5570 //
5571 // FIXME: handle "template <> friend class A<T>;", which
5572 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00005573 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00005574 Diag(Loc, diag::err_tagless_friend_type_template)
5575 << DS.getSourceRange();
5576 return DeclPtrTy();
5577 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005578
John McCallaa74a0c2009-08-28 07:59:38 +00005579 // C++98 [class.friend]p1: A friend of a class is a function
5580 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005581 // This is fixed in DR77, which just barely didn't make the C++03
5582 // deadline. It's also a very silly restriction that seriously
5583 // affects inner classes and which nobody else seems to implement;
5584 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00005585 //
5586 // But note that we could warn about it: it's always useless to
5587 // friend one of your own members (it's not, however, worthless to
5588 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00005589
John McCall11083da2009-09-16 22:47:08 +00005590 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005591 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00005592 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005593 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00005594 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00005595 TSI,
John McCall11083da2009-09-16 22:47:08 +00005596 DS.getFriendSpecLoc());
5597 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005598 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5599
5600 if (!D)
5601 return DeclPtrTy();
5602
John McCall11083da2009-09-16 22:47:08 +00005603 D->setAccess(AS_public);
5604 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005605
John McCall11083da2009-09-16 22:47:08 +00005606 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005607}
5608
John McCall2f212b32009-09-11 21:02:39 +00005609Sema::DeclPtrTy
5610Sema::ActOnFriendFunctionDecl(Scope *S,
5611 Declarator &D,
5612 bool IsDefinition,
5613 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005614 const DeclSpec &DS = D.getDeclSpec();
5615
5616 assert(DS.isFriendSpecified());
5617 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5618
5619 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005620 TypeSourceInfo *TInfo = 0;
5621 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005622
5623 // C++ [class.friend]p1
5624 // A friend of a class is a function or class....
5625 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005626 // It *doesn't* see through dependent types, which is correct
5627 // according to [temp.arg.type]p3:
5628 // If a declaration acquires a function type through a
5629 // type dependent on a template-parameter and this causes
5630 // a declaration that does not use the syntactic form of a
5631 // function declarator to have a function type, the program
5632 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005633 if (!T->isFunctionType()) {
5634 Diag(Loc, diag::err_unexpected_friend);
5635
5636 // It might be worthwhile to try to recover by creating an
5637 // appropriate declaration.
5638 return DeclPtrTy();
5639 }
5640
5641 // C++ [namespace.memdef]p3
5642 // - If a friend declaration in a non-local class first declares a
5643 // class or function, the friend class or function is a member
5644 // of the innermost enclosing namespace.
5645 // - The name of the friend is not found by simple name lookup
5646 // until a matching declaration is provided in that namespace
5647 // scope (either before or after the class declaration granting
5648 // friendship).
5649 // - If a friend function is called, its name may be found by the
5650 // name lookup that considers functions from namespaces and
5651 // classes associated with the types of the function arguments.
5652 // - When looking for a prior declaration of a class or a function
5653 // declared as a friend, scopes outside the innermost enclosing
5654 // namespace scope are not considered.
5655
John McCallaa74a0c2009-08-28 07:59:38 +00005656 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5657 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005658 assert(Name);
5659
John McCall07e91c02009-08-06 02:15:43 +00005660 // The context we found the declaration in, or in which we should
5661 // create the declaration.
5662 DeclContext *DC;
5663
5664 // FIXME: handle local classes
5665
5666 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005667 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5668 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005669 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5670 DC = computeDeclContext(ScopeQual);
5671
5672 // FIXME: handle dependent contexts
5673 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00005674 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005675
John McCall1f82f242009-11-18 22:49:29 +00005676 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005677
5678 // If searching in that context implicitly found a declaration in
5679 // a different context, treat it like it wasn't found at all.
5680 // TODO: better diagnostics for this case. Suggesting the right
5681 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005682 // FIXME: getRepresentativeDecl() is not right here at all
5683 if (Previous.empty() ||
5684 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005685 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005686 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5687 return DeclPtrTy();
5688 }
5689
5690 // C++ [class.friend]p1: A friend of a class is a function or
5691 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005692 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005693 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5694
John McCall07e91c02009-08-06 02:15:43 +00005695 // Otherwise walk out to the nearest namespace scope looking for matches.
5696 } else {
5697 // TODO: handle local class contexts.
5698
5699 DC = CurContext;
5700 while (true) {
5701 // Skip class contexts. If someone can cite chapter and verse
5702 // for this behavior, that would be nice --- it's what GCC and
5703 // EDG do, and it seems like a reasonable intent, but the spec
5704 // really only says that checks for unqualified existing
5705 // declarations should stop at the nearest enclosing namespace,
5706 // not that they should only consider the nearest enclosing
5707 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005708 while (DC->isRecord())
5709 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005710
John McCall1f82f242009-11-18 22:49:29 +00005711 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005712
5713 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005714 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005715 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005716
John McCall07e91c02009-08-06 02:15:43 +00005717 if (DC->isFileContext()) break;
5718 DC = DC->getParent();
5719 }
5720
5721 // C++ [class.friend]p1: A friend of a class is a function or
5722 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005723 // C++0x changes this for both friend types and functions.
5724 // Most C++ 98 compilers do seem to give an error here, so
5725 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005726 if (!Previous.empty() && DC->Equals(CurContext)
5727 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005728 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5729 }
5730
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005731 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005732 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005733 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5734 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5735 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005736 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005737 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5738 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005739 return DeclPtrTy();
5740 }
John McCall07e91c02009-08-06 02:15:43 +00005741 }
5742
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005743 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005744 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005745 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005746 IsDefinition,
5747 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005748 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005749
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005750 assert(ND->getDeclContext() == DC);
5751 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005752
John McCall759e32b2009-08-31 22:39:49 +00005753 // Add the function declaration to the appropriate lookup tables,
5754 // adjusting the redeclarations list as necessary. We don't
5755 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005756 //
John McCall759e32b2009-08-31 22:39:49 +00005757 // Also update the scope-based lookup if the target context's
5758 // lookup context is in lexical scope.
5759 if (!CurContext->isDependentContext()) {
5760 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005761 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005762 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005763 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005764 }
John McCallaa74a0c2009-08-28 07:59:38 +00005765
5766 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005767 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005768 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005769 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005770 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005771
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005772 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005773}
5774
Chris Lattner83f095c2009-03-28 19:18:32 +00005775void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005776 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005777
Chris Lattner83f095c2009-03-28 19:18:32 +00005778 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005779 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5780 if (!Fn) {
5781 Diag(DelLoc, diag::err_deleted_non_function);
5782 return;
5783 }
5784 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5785 Diag(DelLoc, diag::err_deleted_decl_not_first);
5786 Diag(Prev->getLocation(), diag::note_previous_declaration);
5787 // If the declaration wasn't the first, we delete the function anyway for
5788 // recovery.
5789 }
5790 Fn->setDeleted();
5791}
Sebastian Redl4c018662009-04-27 21:33:24 +00005792
5793static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5794 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5795 ++CI) {
5796 Stmt *SubStmt = *CI;
5797 if (!SubStmt)
5798 continue;
5799 if (isa<ReturnStmt>(SubStmt))
5800 Self.Diag(SubStmt->getSourceRange().getBegin(),
5801 diag::err_return_in_constructor_handler);
5802 if (!isa<Expr>(SubStmt))
5803 SearchForReturnInStmt(Self, SubStmt);
5804 }
5805}
5806
5807void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5808 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5809 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5810 SearchForReturnInStmt(*this, Handler);
5811 }
5812}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005813
Mike Stump11289f42009-09-09 15:08:12 +00005814bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005815 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005816 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5817 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005818
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005819 if (Context.hasSameType(NewTy, OldTy) ||
5820 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005821 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005822
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005823 // Check if the return types are covariant
5824 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005825
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005826 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005827 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5828 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005829 NewClassTy = NewPT->getPointeeType();
5830 OldClassTy = OldPT->getPointeeType();
5831 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005832 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5833 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5834 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5835 NewClassTy = NewRT->getPointeeType();
5836 OldClassTy = OldRT->getPointeeType();
5837 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005838 }
5839 }
Mike Stump11289f42009-09-09 15:08:12 +00005840
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005841 // The return types aren't either both pointers or references to a class type.
5842 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005843 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005844 diag::err_different_return_type_for_overriding_virtual_function)
5845 << New->getDeclName() << NewTy << OldTy;
5846 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005847
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005848 return true;
5849 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005850
Anders Carlssone60365b2009-12-31 18:34:24 +00005851 // C++ [class.virtual]p6:
5852 // If the return type of D::f differs from the return type of B::f, the
5853 // class type in the return type of D::f shall be complete at the point of
5854 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005855 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5856 if (!RT->isBeingDefined() &&
5857 RequireCompleteType(New->getLocation(), NewClassTy,
5858 PDiag(diag::err_covariant_return_incomplete)
5859 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005860 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005861 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005862
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005863 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005864 // Check if the new class derives from the old class.
5865 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5866 Diag(New->getLocation(),
5867 diag::err_covariant_return_not_derived)
5868 << New->getDeclName() << NewTy << OldTy;
5869 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5870 return true;
5871 }
Mike Stump11289f42009-09-09 15:08:12 +00005872
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005873 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00005874 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00005875 diag::err_covariant_return_inaccessible_base,
5876 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5877 // FIXME: Should this point to the return type?
5878 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005879 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5880 return true;
5881 }
5882 }
Mike Stump11289f42009-09-09 15:08:12 +00005883
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005884 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005885 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005886 Diag(New->getLocation(),
5887 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005888 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005889 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5890 return true;
5891 };
Mike Stump11289f42009-09-09 15:08:12 +00005892
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005893
5894 // The new class type must have the same or less qualifiers as the old type.
5895 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5896 Diag(New->getLocation(),
5897 diag::err_covariant_return_type_class_type_more_qualified)
5898 << New->getDeclName() << NewTy << OldTy;
5899 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5900 return true;
5901 };
Mike Stump11289f42009-09-09 15:08:12 +00005902
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005903 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005904}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005905
Alexis Hunt96d5c762009-11-21 08:43:09 +00005906bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5907 const CXXMethodDecl *Old)
5908{
5909 if (Old->hasAttr<FinalAttr>()) {
5910 Diag(New->getLocation(), diag::err_final_function_overridden)
5911 << New->getDeclName();
5912 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5913 return true;
5914 }
5915
5916 return false;
5917}
5918
Douglas Gregor21920e372009-12-01 17:24:26 +00005919/// \brief Mark the given method pure.
5920///
5921/// \param Method the method to be marked pure.
5922///
5923/// \param InitRange the source range that covers the "0" initializer.
5924bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5925 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5926 Method->setPure();
5927
5928 // A class is abstract if at least one function is pure virtual.
5929 Method->getParent()->setAbstract(true);
5930 return false;
5931 }
5932
5933 if (!Method->isInvalidDecl())
5934 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5935 << Method->getDeclName() << InitRange;
5936 return true;
5937}
5938
John McCall1f4ee7b2009-12-19 09:28:58 +00005939/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5940/// an initializer for the out-of-line declaration 'Dcl'. The scope
5941/// is a fresh scope pushed for just this purpose.
5942///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005943/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5944/// static data member of class X, names should be looked up in the scope of
5945/// class X.
5946void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005947 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005948 Decl *D = Dcl.getAs<Decl>();
5949 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005950
John McCall1f4ee7b2009-12-19 09:28:58 +00005951 // We should only get called for declarations with scope specifiers, like:
5952 // int foo::bar;
5953 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005954 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005955}
5956
5957/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005958/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005959void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005960 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005961 Decl *D = Dcl.getAs<Decl>();
5962 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005963
John McCall1f4ee7b2009-12-19 09:28:58 +00005964 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005965 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005966}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005967
5968/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5969/// C++ if/switch/while/for statement.
5970/// e.g: "if (int x = f()) {...}"
5971Action::DeclResult
5972Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5973 // C++ 6.4p2:
5974 // The declarator shall not specify a function or an array.
5975 // The type-specifier-seq shall not contain typedef and shall not declare a
5976 // new class or enumeration.
5977 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5978 "Parser allowed 'typedef' as storage class of condition decl.");
5979
John McCallbcd03502009-12-07 02:54:59 +00005980 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005981 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005982 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005983
5984 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5985 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5986 // would be created and CXXConditionDeclExpr wants a VarDecl.
5987 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5988 << D.getSourceRange();
5989 return DeclResult();
5990 } else if (OwnedTag && OwnedTag->isDefinition()) {
5991 // The type-specifier-seq shall not declare a new class or enumeration.
5992 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5993 }
5994
5995 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5996 if (!Dcl)
5997 return DeclResult();
5998
5999 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
6000 VD->setDeclaredInCondition(true);
6001 return Dcl;
6002}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006003
Anders Carlsson11e51402010-04-17 20:15:18 +00006004static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00006005 // Ignore dependent types.
6006 if (MD->isDependentContext())
Rafael Espindola70e040d2010-03-02 21:28:26 +00006007 return false;
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00006008
Douglas Gregorccecc1b2010-01-06 20:27:16 +00006009 // Ignore declarations that are not definitions.
6010 if (!MD->isThisDeclarationADefinition())
Rafael Espindola70e040d2010-03-02 21:28:26 +00006011 return false;
6012
6013 CXXRecordDecl *RD = MD->getParent();
6014
6015 // Ignore classes without a vtable.
6016 if (!RD->isDynamicClass())
6017 return false;
6018
6019 switch (MD->getParent()->getTemplateSpecializationKind()) {
6020 case TSK_Undeclared:
6021 case TSK_ExplicitSpecialization:
6022 // Classes that aren't instantiations of templates don't need their
6023 // virtual methods marked until we see the definition of the key
6024 // function.
6025 break;
6026
6027 case TSK_ImplicitInstantiation:
6028 // This is a constructor of a class template; mark all of the virtual
6029 // members as referenced to ensure that they get instantiatied.
6030 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
6031 return true;
6032 break;
6033
6034 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola8d04f062010-03-22 23:12:48 +00006035 return false;
Rafael Espindola70e040d2010-03-02 21:28:26 +00006036
6037 case TSK_ExplicitInstantiationDefinition:
6038 // This is method of a explicit instantiation; mark all of the virtual
6039 // members as referenced to ensure that they get instantiatied.
6040 return true;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00006041 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00006042
6043 // Consider only out-of-line definitions of member functions. When we see
6044 // an inline definition, it's too early to compute the key function.
6045 if (!MD->isOutOfLine())
6046 return false;
6047
6048 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
6049
6050 // If there is no key function, we will need a copy of the vtable.
6051 if (!KeyFunction)
6052 return true;
6053
6054 // If this is the key function, we need to mark virtual members.
6055 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
6056 return true;
6057
6058 return false;
6059}
6060
6061void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
6062 CXXMethodDecl *MD) {
6063 CXXRecordDecl *RD = MD->getParent();
6064
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00006065 // We will need to mark all of the virtual members as referenced to build the
6066 // vtable.
Anders Carlsson11e51402010-04-17 20:15:18 +00006067 if (!needsVTable(MD, Context))
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006068 return;
6069
6070 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
6071 if (kind == TSK_ImplicitInstantiation)
6072 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
6073 else
Rafael Espindola70e040d2010-03-02 21:28:26 +00006074 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson82fccd02009-12-07 08:24:59 +00006075}
6076
6077bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
6078 if (ClassesWithUnmarkedVirtualMembers.empty())
6079 return false;
6080
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00006081 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
6082 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
6083 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
6084 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00006085 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006086 }
6087
Anders Carlsson82fccd02009-12-07 08:24:59 +00006088 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006089}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006090
Rafael Espindola5b334082010-03-26 00:36:59 +00006091void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6092 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006093 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6094 e = RD->method_end(); i != e; ++i) {
6095 CXXMethodDecl *MD = *i;
6096
6097 // C++ [basic.def.odr]p2:
6098 // [...] A virtual member function is used if it is not pure. [...]
6099 if (MD->isVirtual() && !MD->isPure())
6100 MarkDeclarationReferenced(Loc, MD);
6101 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006102
6103 // Only classes that have virtual bases need a VTT.
6104 if (RD->getNumVBases() == 0)
6105 return;
6106
6107 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6108 e = RD->bases_end(); i != e; ++i) {
6109 const CXXRecordDecl *Base =
6110 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6111 if (i->isVirtual())
6112 continue;
6113 if (Base->getNumVBases() == 0)
6114 continue;
6115 MarkVirtualMembersReferenced(Loc, Base);
6116 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006117}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006118
6119/// SetIvarInitializers - This routine builds initialization ASTs for the
6120/// Objective-C implementation whose ivars need be initialized.
6121void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6122 if (!getLangOptions().CPlusPlus)
6123 return;
6124 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6125 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6126 CollectIvarsToConstructOrDestruct(OID, ivars);
6127 if (ivars.empty())
6128 return;
6129 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6130 for (unsigned i = 0; i < ivars.size(); i++) {
6131 FieldDecl *Field = ivars[i];
6132 CXXBaseOrMemberInitializer *Member;
6133 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6134 InitializationKind InitKind =
6135 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6136
6137 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6138 Sema::OwningExprResult MemberInit =
6139 InitSeq.Perform(*this, InitEntity, InitKind,
6140 Sema::MultiExprArg(*this, 0, 0));
6141 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6142 // Note, MemberInit could actually come back empty if no initialization
6143 // is required (e.g., because it would call a trivial default constructor)
6144 if (!MemberInit.get() || MemberInit.isInvalid())
6145 continue;
6146
6147 Member =
6148 new (Context) CXXBaseOrMemberInitializer(Context,
6149 Field, SourceLocation(),
6150 SourceLocation(),
6151 MemberInit.takeAs<Expr>(),
6152 SourceLocation());
6153 AllToInit.push_back(Member);
6154 }
6155 ObjCImplementation->setIvarInitializers(Context,
6156 AllToInit.data(), AllToInit.size());
6157 }
6158}