blob: b32055a8a44ca8befc00f1d295a17dd26f050fd0 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000019#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000025#include "clang/AST/TypeOrdering.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000026#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000031#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000032#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000033
34using namespace clang;
35
Chris Lattner8123a952008-04-10 02:22:51 +000036//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
Chris Lattner9e979552008-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 Kramer85b45212009-11-28 19:45:26 +000046 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000048 Expr *DefaultArg;
49 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 public:
Mike Stump1eb44332009-09-09 15:08:12 +000052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000053 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-04-12 23:52:44 +000055 bool VisitExpr(Expr *Node);
56 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000057 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000058 };
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000063 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000064 E = Node->child_end(); I != E; ++I)
65 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000066 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000067 }
68
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000073 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000083 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000084 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000085 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000087 // C++ [dcl.fct.default]p7
88 // Local variables shall not be used in default argument
89 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000090 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000091 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000094 }
Chris Lattner8123a952008-04-10 02:22:51 +000095
Douglas Gregor3996f232008-11-04 13:41:56 +000096 return false;
97 }
Chris Lattner9e979552008-04-12 23:52:44 +000098
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_this)
106 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000107 }
Chris Lattner8123a952008-04-10 02:22:51 +0000108}
109
Anders Carlssoned961f92009-08-25 02:29:20 +0000110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000112 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-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 Carlssoned961f92009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Anders Carlssoned961f92009-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 Gregor99a2e602009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman4a2c19b2009-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 Carlsson9351c172009-08-25 03:18:48 +0000134 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000136
Anders Carlsson0ece4912009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Anders Carlssoned961f92009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson9351c172009-08-25 03:18:48 +0000144 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000145}
146
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000150void
Mike Stump1eb44332009-09-09 15:08:12 +0000151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000153 if (!param || !defarg.get())
154 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Chris Lattnerb28317a2009-03-28 19:18:32 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000160
161 // Default arguments are only permitted in C++
162 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000163 Diag(EqualLoc, diag::err_param_default_argument)
164 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000165 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000166 return;
167 }
168
Anders Carlsson66e30672009-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 Stump1eb44332009-09-09 15:08:12 +0000175
Anders Carlssoned961f92009-08-25 02:29:20 +0000176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177}
178
Douglas Gregor61366e92008-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 Stump1eb44332009-09-09 15:08:12 +0000183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000184 SourceLocation EqualLoc,
185 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000186 if (!param)
187 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Chris Lattnerb28317a2009-03-28 19:18:32 +0000189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000190 if (Param)
191 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Anders Carlsson5e300d12009-06-12 16:51:40 +0000193 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000194}
195
Douglas Gregor72b505b2008-12-16 21:30:33 +0000196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000199 if (!param)
200 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlsson5e300d12009-06-12 16:51:40 +0000202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Anders Carlsson5e300d12009-06-12 16:51:40 +0000206 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000207}
208
Douglas Gregor6d6eb572008-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 Lattnerb28317a2009-03-28 19:18:32 +0000222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000223 DeclaratorChunk &chunk = D.getTypeObject(i);
224 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-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 Gregor61366e92008-12-24 00:01:03 +0000228 if (Param->hasUnparsedDefaultArg()) {
229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-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 Gregor61366e92008-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 Gregor6d6eb572008-05-07 04:49:29 +0000238 }
239 }
240 }
241 }
242}
243
Chris Lattner3d1cee32008-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 Gregorcda9c672009-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 Lattner3d1cee32008-04-08 05:04:30 +0000251 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-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 Gregor6cc15182009-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 Lattner3d1cee32008-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 Gregor6cc15182009-09-11 18:44:32 +0000273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-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 Stump1eb44332009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000285 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-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 Gregorcda9c672009-02-16 17:45:42 +0000299 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000300 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-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 McCallbf73b352010-03-12 18:31:32 +0000304 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000305 if (OldParam->hasUninstantiatedDefaultArg())
306 NewParam->setUninstantiatedDefaultArg(
307 OldParam->getUninstantiatedDefaultArg());
308 else
John McCall3d6c1782010-05-04 01:53:42 +0000309 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-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 Gregor096ebfd2009-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 Gregor8c638ab2009-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 Gregor096ebfd2009-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 Gregor6cc15182009-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 Lattner3d1cee32008-04-08 05:04:30 +0000360 }
361 }
362
Douglas Gregore13ad832010-02-12 07:32:17 +0000363 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000364 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000365
Douglas Gregorcda9c672009-02-16 17:45:42 +0000366 return Invalid;
Chris Lattner3d1cee32008-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 Carlsson5f49a0c2009-08-25 01:23:32 +0000379 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-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 Stump1eb44332009-09-09 15:08:12 +0000390 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000391 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000392 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 if (Param->isInvalidDecl())
394 /* We already complained about this parameter. */;
395 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000397 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000398 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 else
Mike Stump1eb44332009-09-09 15:08:12 +0000400 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner3d1cee32008-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 Carlsson5e300d12009-06-12 16:51:40 +0000414 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000415 if (!Param->hasUnparsedDefaultArg())
416 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000417 Param->setDefaultArg(0);
418 }
419 }
420 }
421}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000422
Douglas Gregorb48fe382008-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 Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000427bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
428 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000429 assert(getLangOptions().CPlusPlus && "No class names in C!");
430
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000431 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000432 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000433 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-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 Gregor6f7a17b2010-02-05 06:12:42 +0000438 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000439 return &II == CurDecl->getIdentifier();
440 else
441 return false;
442}
443
Mike Stump1eb44332009-09-09 15:08:12 +0000444/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-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 Stump1eb44332009-09-09 15:08:12 +0000452 QualType BaseType,
Douglas Gregor2943aed2009-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 Stump1eb44332009-09-09 15:08:12 +0000463 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000464 Class->getTagKind() == TTK_Class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000465 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 Stump1eb44332009-09-09 15:08:12 +0000483 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000484 PDiag(diag::err_incomplete_base_class)
485 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 return 0;
487
Eli Friedman1d954f62009-08-15 21:55:26 +0000488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000491 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000495
Sean Huntbbd37c62009-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 Gregor9af2f522009-12-01 16:58:18 +0000499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000501 return 0;
502 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000503
Eli Friedmand0137332009-12-05 23:03:49 +0000504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000505
506 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000507 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000508 Class->getTagKind() == TTK_Class,
Anders Carlsson51f94042009-12-03 17:49:57 +0000509 Access, BaseType);
510}
511
512void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
513 const CXXRecordDecl *BaseClass,
514 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000515 // A class with a non-empty base class is not empty.
516 // FIXME: Standard ref?
517 if (!BaseClass->isEmpty())
518 Class->setEmpty(false);
519
520 // C++ [class.virtual]p1:
521 // A class that [...] inherits a virtual function is called a polymorphic
522 // class.
523 if (BaseClass->isPolymorphic())
524 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000525
Douglas Gregor2943aed2009-03-03 04:44:36 +0000526 // C++ [dcl.init.aggr]p1:
527 // An aggregate is [...] a class with [...] no base classes [...].
528 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000529
530 // C++ [class]p4:
531 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000532 Class->setPOD(false);
533
Anders Carlsson51f94042009-12-03 17:49:57 +0000534 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000535 // C++ [class.ctor]p5:
536 // A constructor is trivial if its class has no virtual base classes.
537 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000538
539 // C++ [class.copy]p6:
540 // A copy constructor is trivial if its class has no virtual base classes.
541 Class->setHasTrivialCopyConstructor(false);
542
543 // C++ [class.copy]p11:
544 // A copy assignment operator is trivial if its class has no virtual
545 // base classes.
546 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000547
548 // C++0x [meta.unary.prop] is_empty:
549 // T is a class type, but not a union type, with ... no virtual base
550 // classes
551 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 } else {
553 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000554 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000555 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000556 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000557 Class->setHasTrivialConstructor(false);
558
559 // C++ [class.copy]p6:
560 // A copy constructor is trivial if all the direct base classes of its
561 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000563 Class->setHasTrivialCopyConstructor(false);
564
565 // C++ [class.copy]p11:
566 // A copy assignment operator is trivial if all the direct base classes
567 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000568 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000569 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000570 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000571
572 // C++ [class.ctor]p3:
573 // A destructor is trivial if all the direct base classes of its class
574 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000575 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000576 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577}
578
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000579/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
580/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000581/// example:
582/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000583/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000584Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000585Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000586 bool Virtual, AccessSpecifier Access,
587 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000588 if (!classdecl)
589 return true;
590
Douglas Gregor40808ce2009-03-09 23:48:35 +0000591 AdjustDeclIfTemplate(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000592 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
593 if (!Class)
594 return true;
595
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000596 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
598 Virtual, Access,
599 BaseType, BaseLoc))
600 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Douglas Gregor2943aed2009-03-03 04:44:36 +0000602 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregor2943aed2009-03-03 04:44:36 +0000605/// \brief Performs the actual work of attaching the given base class
606/// specifiers to a C++ class.
607bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
608 unsigned NumBases) {
609 if (NumBases == 0)
610 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000611
612 // Used to keep track of which base types we have already seen, so
613 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000614 // that the key is always the unqualified canonical type of the base
615 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000616 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
617
618 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000621 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000622 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000623 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000624 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000625
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000626 if (KnownBaseTypes[NewBaseType]) {
627 // C++ [class.mi]p3:
628 // A class shall not be specified as a direct base class of a
629 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000630 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000631 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000632 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000634
635 // Delete the duplicate base class specifier; we're going to
636 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000637 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638
639 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000640 } else {
641 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 KnownBaseTypes[NewBaseType] = Bases[idx];
643 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000644 }
645 }
646
647 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000648 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000649
650 // Delete the remaining (good) base class specifiers, since their
651 // data has been copied into the CXXRecordDecl.
652 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000653 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000654
655 return Invalid;
656}
657
658/// ActOnBaseSpecifiers - Attach the given base specifiers to the
659/// class, after checking whether there are any duplicate base
660/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000661void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 unsigned NumBases) {
663 if (!ClassDecl || !Bases || !NumBases)
664 return;
665
666 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000667 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000668 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000669}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000670
John McCall3cb0ebd2010-03-10 03:28:59 +0000671static CXXRecordDecl *GetClassForType(QualType T) {
672 if (const RecordType *RT = T->getAs<RecordType>())
673 return cast<CXXRecordDecl>(RT->getDecl());
674 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
675 return ICT->getDecl();
676 else
677 return 0;
678}
679
Douglas Gregora8f32e02009-10-06 17:59:45 +0000680/// \brief Determine whether the type \p Derived is a C++ class that is
681/// derived from the type \p Base.
682bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
683 if (!getLangOptions().CPlusPlus)
684 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000685
686 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
687 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000688 return false;
689
John McCall3cb0ebd2010-03-10 03:28:59 +0000690 CXXRecordDecl *BaseRD = GetClassForType(Base);
691 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000692 return false;
693
John McCall86ff3082010-02-04 22:26:26 +0000694 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
695 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000696}
697
698/// \brief Determine whether the type \p Derived is a C++ class that is
699/// derived from the type \p Base.
700bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
701 if (!getLangOptions().CPlusPlus)
702 return false;
703
John McCall3cb0ebd2010-03-10 03:28:59 +0000704 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
705 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000706 return false;
707
John McCall3cb0ebd2010-03-10 03:28:59 +0000708 CXXRecordDecl *BaseRD = GetClassForType(Base);
709 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000710 return false;
711
Douglas Gregora8f32e02009-10-06 17:59:45 +0000712 return DerivedRD->isDerivedFrom(BaseRD, Paths);
713}
714
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000715void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
716 CXXBaseSpecifierArray &BasePathArray) {
717 assert(BasePathArray.empty() && "Base path array must be empty!");
718 assert(Paths.isRecordingPaths() && "Must record paths!");
719
720 const CXXBasePath &Path = Paths.front();
721
722 // We first go backward and check if we have a virtual base.
723 // FIXME: It would be better if CXXBasePath had the base specifier for
724 // the nearest virtual base.
725 unsigned Start = 0;
726 for (unsigned I = Path.size(); I != 0; --I) {
727 if (Path[I - 1].Base->isVirtual()) {
728 Start = I - 1;
729 break;
730 }
731 }
732
733 // Now add all bases.
734 for (unsigned I = Start, E = Path.size(); I != E; ++I)
735 BasePathArray.push_back(Path[I].Base);
736}
737
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000738/// \brief Determine whether the given base path includes a virtual
739/// base class.
740bool Sema::BasePathInvolvesVirtualBase(const CXXBaseSpecifierArray &BasePath) {
741 for (CXXBaseSpecifierArray::iterator B = BasePath.begin(),
742 BEnd = BasePath.end();
743 B != BEnd; ++B)
744 if ((*B)->isVirtual())
745 return true;
746
747 return false;
748}
749
Douglas Gregora8f32e02009-10-06 17:59:45 +0000750/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
751/// conversion (where Derived and Base are class types) is
752/// well-formed, meaning that the conversion is unambiguous (and
753/// that all of the base classes are accessible). Returns true
754/// and emits a diagnostic if the code is ill-formed, returns false
755/// otherwise. Loc is the location where this routine should point to
756/// if there is an error, and Range is the source range to highlight
757/// if there is an error.
758bool
759Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000760 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000761 unsigned AmbigiousBaseConvID,
762 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000763 DeclarationName Name,
764 CXXBaseSpecifierArray *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000765 // First, determine whether the path from Derived to Base is
766 // ambiguous. This is slightly more expensive than checking whether
767 // the Derived to Base conversion exists, because here we need to
768 // explore multiple paths to determine if there is an ambiguity.
769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
770 /*DetectVirtual=*/false);
771 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
772 assert(DerivationOkay &&
773 "Can only be used with a derived-to-base conversion");
774 (void)DerivationOkay;
775
776 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000777 if (InaccessibleBaseID) {
778 // Check that the base class can be accessed.
779 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
780 InaccessibleBaseID)) {
781 case AR_inaccessible:
782 return true;
783 case AR_accessible:
784 case AR_dependent:
785 case AR_delayed:
786 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000787 }
John McCall6b2accb2010-02-10 09:31:12 +0000788 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000789
790 // Build a base path if necessary.
791 if (BasePath)
792 BuildBasePathArray(Paths, *BasePath);
793 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000794 }
795
796 // We know that the derived-to-base conversion is ambiguous, and
797 // we're going to produce a diagnostic. Perform the derived-to-base
798 // search just one more time to compute all of the possible paths so
799 // that we can print them out. This is more expensive than any of
800 // the previous derived-to-base checks we've done, but at this point
801 // performance isn't as much of an issue.
802 Paths.clear();
803 Paths.setRecordingPaths(true);
804 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
805 assert(StillOkay && "Can only be used with a derived-to-base conversion");
806 (void)StillOkay;
807
808 // Build up a textual representation of the ambiguous paths, e.g.,
809 // D -> B -> A, that will be used to illustrate the ambiguous
810 // conversions in the diagnostic. We only print one of the paths
811 // to each base class subobject.
812 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
813
814 Diag(Loc, AmbigiousBaseConvID)
815 << Derived << Base << PathDisplayStr << Range << Name;
816 return true;
817}
818
819bool
820Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000821 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000822 CXXBaseSpecifierArray *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000823 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000824 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000825 IgnoreAccess ? 0
826 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000828 Loc, Range, DeclarationName(),
829 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000830}
831
832
833/// @brief Builds a string representing ambiguous paths from a
834/// specific derived class to different subobjects of the same base
835/// class.
836///
837/// This function builds a string that can be used in error messages
838/// to show the different paths that one can take through the
839/// inheritance hierarchy to go from the derived class to different
840/// subobjects of a base class. The result looks something like this:
841/// @code
842/// struct D -> struct B -> struct A
843/// struct D -> struct C -> struct A
844/// @endcode
845std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
846 std::string PathDisplayStr;
847 std::set<unsigned> DisplayedPaths;
848 for (CXXBasePaths::paths_iterator Path = Paths.begin();
849 Path != Paths.end(); ++Path) {
850 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
851 // We haven't displayed a path to this particular base
852 // class subobject yet.
853 PathDisplayStr += "\n ";
854 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
855 for (CXXBasePath::const_iterator Element = Path->begin();
856 Element != Path->end(); ++Element)
857 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
858 }
859 }
860
861 return PathDisplayStr;
862}
863
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864//===----------------------------------------------------------------------===//
865// C++ class member Handling
866//===----------------------------------------------------------------------===//
867
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000868/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
869/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
870/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000871/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000872Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000874 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000875 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
876 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000877 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000878 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000879 Expr *BitWidth = static_cast<Expr*>(BW);
880 Expr *Init = static_cast<Expr*>(InitExpr);
881 SourceLocation Loc = D.getIdentifierLoc();
882
Sebastian Redl669d5d72008-11-14 23:42:31 +0000883 bool isFunc = D.isFunctionDeclarator();
884
John McCall67d1a672009-08-06 02:15:43 +0000885 assert(!DS.isFriendSpecified());
886
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000887 // C++ 9.2p6: A member shall not be declared to have automatic storage
888 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000889 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
890 // data members and cannot be applied to names declared const or static,
891 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000892 switch (DS.getStorageClassSpec()) {
893 case DeclSpec::SCS_unspecified:
894 case DeclSpec::SCS_typedef:
895 case DeclSpec::SCS_static:
896 // FALL THROUGH.
897 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000898 case DeclSpec::SCS_mutable:
899 if (isFunc) {
900 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000901 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000902 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000903 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Sebastian Redla11f42f2008-11-17 23:24:37 +0000905 // FIXME: It would be nicer if the keyword was ignored only for this
906 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000907 D.getMutableDeclSpec().ClearStorageClassSpecs();
908 } else {
909 QualType T = GetTypeForDeclarator(D, S);
910 diag::kind err = static_cast<diag::kind>(0);
911 if (T->isReferenceType())
912 err = diag::err_mutable_reference;
913 else if (T.isConstQualified())
914 err = diag::err_mutable_const;
915 if (err != 0) {
916 if (DS.getStorageClassSpecLoc().isValid())
917 Diag(DS.getStorageClassSpecLoc(), err);
918 else
919 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000920 // FIXME: It would be nicer if the keyword was ignored only for this
921 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000922 D.getMutableDeclSpec().ClearStorageClassSpecs();
923 }
924 }
925 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000926 default:
927 if (DS.getStorageClassSpecLoc().isValid())
928 Diag(DS.getStorageClassSpecLoc(),
929 diag::err_storageclass_invalid_for_member);
930 else
931 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
932 D.getMutableDeclSpec().ClearStorageClassSpecs();
933 }
934
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000935 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000936 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000937 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000938 // Check also for this case:
939 //
940 // typedef int f();
941 // f a;
942 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000943 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000944 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000945 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000946
Sebastian Redl669d5d72008-11-14 23:42:31 +0000947 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
948 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000949 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000950
951 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000952 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000953 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000954 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
955 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000956 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000957 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000958 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000959 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000960 if (!Member) {
961 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000962 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000963 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000964
965 // Non-instance-fields can't have a bitfield.
966 if (BitWidth) {
967 if (Member->isInvalidDecl()) {
968 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000969 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000970 // C++ 9.6p3: A bit-field shall not be a static member.
971 // "static member 'A' cannot be a bit-field"
972 Diag(Loc, diag::err_static_not_bitfield)
973 << Name << BitWidth->getSourceRange();
974 } else if (isa<TypedefDecl>(Member)) {
975 // "typedef member 'x' cannot be a bit-field"
976 Diag(Loc, diag::err_typedef_not_bitfield)
977 << Name << BitWidth->getSourceRange();
978 } else {
979 // A function typedef ("typedef int f(); f a;").
980 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
981 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000982 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000983 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000984 }
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner8b963ef2009-03-05 23:01:03 +0000986 DeleteExpr(BitWidth);
987 BitWidth = 0;
988 Member->setInvalidDecl();
989 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000990
991 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Douglas Gregor37b372b2009-08-20 22:52:58 +0000993 // If we have declared a member function template, set the access of the
994 // templated declaration as well.
995 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
996 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000997 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000998
Douglas Gregor10bd3682008-11-17 22:58:34 +0000999 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001000
Douglas Gregor021c3b32009-03-11 23:00:04 +00001001 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +00001002 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001003 if (Deleted) // FIXME: Source location is not very good.
1004 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001005
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001006 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001007 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +00001008 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001009 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00001010 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001011}
1012
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001013/// \brief Find the direct and/or virtual base specifiers that
1014/// correspond to the given base type, for use in base initialization
1015/// within a constructor.
1016static bool FindBaseInitializer(Sema &SemaRef,
1017 CXXRecordDecl *ClassDecl,
1018 QualType BaseType,
1019 const CXXBaseSpecifier *&DirectBaseSpec,
1020 const CXXBaseSpecifier *&VirtualBaseSpec) {
1021 // First, check for a direct base class.
1022 DirectBaseSpec = 0;
1023 for (CXXRecordDecl::base_class_const_iterator Base
1024 = ClassDecl->bases_begin();
1025 Base != ClassDecl->bases_end(); ++Base) {
1026 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1027 // We found a direct base of this type. That's what we're
1028 // initializing.
1029 DirectBaseSpec = &*Base;
1030 break;
1031 }
1032 }
1033
1034 // Check for a virtual base class.
1035 // FIXME: We might be able to short-circuit this if we know in advance that
1036 // there are no virtual bases.
1037 VirtualBaseSpec = 0;
1038 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1039 // We haven't found a base yet; search the class hierarchy for a
1040 // virtual base class.
1041 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1042 /*DetectVirtual=*/false);
1043 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1044 BaseType, Paths)) {
1045 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1046 Path != Paths.end(); ++Path) {
1047 if (Path->back().Base->isVirtual()) {
1048 VirtualBaseSpec = Path->back().Base;
1049 break;
1050 }
1051 }
1052 }
1053 }
1054
1055 return DirectBaseSpec || VirtualBaseSpec;
1056}
1057
Douglas Gregor7ad83902008-11-05 04:29:56 +00001058/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001059Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001060Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001062 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001063 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001064 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001065 SourceLocation IdLoc,
1066 SourceLocation LParenLoc,
1067 ExprTy **Args, unsigned NumArgs,
1068 SourceLocation *CommaLocs,
1069 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001070 if (!ConstructorD)
1071 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001073 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
1075 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001076 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001077 if (!Constructor) {
1078 // The user wrote a constructor initializer on a function that is
1079 // not a C++ constructor. Ignore the error for now, because we may
1080 // have more member initializers coming; we'll diagnose it just
1081 // once in ActOnMemInitializers.
1082 return true;
1083 }
1084
1085 CXXRecordDecl *ClassDecl = Constructor->getParent();
1086
1087 // C++ [class.base.init]p2:
1088 // Names in a mem-initializer-id are looked up in the scope of the
1089 // constructor’s class and, if not found in that scope, are looked
1090 // up in the scope containing the constructor’s
1091 // definition. [Note: if the constructor’s class contains a member
1092 // with the same name as a direct or virtual base class of the
1093 // class, a mem-initializer-id naming the member or base class and
1094 // composed of a single identifier refers to the class member. A
1095 // mem-initializer-id for the hidden base class may be specified
1096 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001097 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001098 // Look for a member, first.
1099 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001100 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001101 = ClassDecl->lookup(MemberOrBase);
1102 if (Result.first != Result.second)
1103 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001104
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001105 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001106
Eli Friedman59c04372009-07-29 19:44:27 +00001107 if (Member)
1108 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001109 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001110 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001111 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001112 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001113 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001114
1115 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001116 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001117 } else {
1118 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1119 LookupParsedName(R, S, &SS);
1120
1121 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1122 if (!TyD) {
1123 if (R.isAmbiguous()) return true;
1124
John McCallfd225442010-04-09 19:01:14 +00001125 // We don't want access-control diagnostics here.
1126 R.suppressDiagnostics();
1127
Douglas Gregor7a886e12010-01-19 06:46:48 +00001128 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1129 bool NotUnknownSpecialization = false;
1130 DeclContext *DC = computeDeclContext(SS, false);
1131 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1132 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1133
1134 if (!NotUnknownSpecialization) {
1135 // When the scope specifier can refer to a member of an unknown
1136 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001137 BaseType = CheckTypenameType(ETK_None,
1138 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001139 *MemberOrBase, SourceLocation(),
1140 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001141 if (BaseType.isNull())
1142 return true;
1143
Douglas Gregor7a886e12010-01-19 06:46:48 +00001144 R.clear();
1145 }
1146 }
1147
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001148 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001149 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001150 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1151 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001152 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1153 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1154 // We have found a non-static data member with a similar
1155 // name to what was typed; complain and initialize that
1156 // member.
1157 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1158 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001159 << FixItHint::CreateReplacement(R.getNameLoc(),
1160 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001161 Diag(Member->getLocation(), diag::note_previous_decl)
1162 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001163
1164 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1165 LParenLoc, RParenLoc);
1166 }
1167 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1168 const CXXBaseSpecifier *DirectBaseSpec;
1169 const CXXBaseSpecifier *VirtualBaseSpec;
1170 if (FindBaseInitializer(*this, ClassDecl,
1171 Context.getTypeDeclType(Type),
1172 DirectBaseSpec, VirtualBaseSpec)) {
1173 // We have found a direct or virtual base class with a
1174 // similar name to what was typed; complain and initialize
1175 // that base class.
1176 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1177 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001178 << FixItHint::CreateReplacement(R.getNameLoc(),
1179 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001180
1181 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1182 : VirtualBaseSpec;
1183 Diag(BaseSpec->getSourceRange().getBegin(),
1184 diag::note_base_class_specified_here)
1185 << BaseSpec->getType()
1186 << BaseSpec->getSourceRange();
1187
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001188 TyD = Type;
1189 }
1190 }
1191 }
1192
Douglas Gregor7a886e12010-01-19 06:46:48 +00001193 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001194 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1195 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1196 return true;
1197 }
John McCall2b194412009-12-21 10:41:20 +00001198 }
1199
Douglas Gregor7a886e12010-01-19 06:46:48 +00001200 if (BaseType.isNull()) {
1201 BaseType = Context.getTypeDeclType(TyD);
1202 if (SS.isSet()) {
1203 NestedNameSpecifier *Qualifier =
1204 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001205
Douglas Gregor7a886e12010-01-19 06:46:48 +00001206 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001207 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001208 }
John McCall2b194412009-12-21 10:41:20 +00001209 }
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
John McCalla93c9342009-12-07 02:54:59 +00001212 if (!TInfo)
1213 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001214
John McCalla93c9342009-12-07 02:54:59 +00001215 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001216 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001217}
1218
John McCallb4190042009-11-04 23:02:40 +00001219/// Checks an initializer expression for use of uninitialized fields, such as
1220/// containing the field that is being initialized. Returns true if there is an
1221/// uninitialized field was used an updates the SourceLocation parameter; false
1222/// otherwise.
1223static bool InitExprContainsUninitializedFields(const Stmt* S,
1224 const FieldDecl* LhsField,
1225 SourceLocation* L) {
1226 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1227 if (ME) {
1228 const NamedDecl* RhsField = ME->getMemberDecl();
1229 if (RhsField == LhsField) {
1230 // Initializing a field with itself. Throw a warning.
1231 // But wait; there are exceptions!
1232 // Exception #1: The field may not belong to this record.
1233 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1234 const Expr* base = ME->getBase();
1235 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1236 // Even though the field matches, it does not belong to this record.
1237 return false;
1238 }
1239 // None of the exceptions triggered; return true to indicate an
1240 // uninitialized field was used.
1241 *L = ME->getMemberLoc();
1242 return true;
1243 }
1244 }
1245 bool found = false;
1246 for (Stmt::const_child_iterator it = S->child_begin();
1247 it != S->child_end() && found == false;
1248 ++it) {
1249 if (isa<CallExpr>(S)) {
1250 // Do not descend into function calls or constructors, as the use
1251 // of an uninitialized field may be valid. One would have to inspect
1252 // the contents of the function/ctor to determine if it is safe or not.
1253 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1254 // may be safe, depending on what the function/ctor does.
1255 continue;
1256 }
1257 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1258 }
1259 return found;
1260}
1261
Eli Friedman59c04372009-07-29 19:44:27 +00001262Sema::MemInitResult
1263Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1264 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001265 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001266 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001267 // Diagnose value-uses of fields to initialize themselves, e.g.
1268 // foo(foo)
1269 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001270 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001271 for (unsigned i = 0; i < NumArgs; ++i) {
1272 SourceLocation L;
1273 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1274 // FIXME: Return true in the case when other fields are used before being
1275 // uninitialized. For example, let this field be the i'th field. When
1276 // initializing the i'th field, throw a warning if any of the >= i'th
1277 // fields are used, as they are not yet initialized.
1278 // Right now we are only handling the case where the i'th field uses
1279 // itself in its initializer.
1280 Diag(L, diag::warn_field_is_uninit);
1281 }
1282 }
1283
Eli Friedman59c04372009-07-29 19:44:27 +00001284 bool HasDependentArg = false;
1285 for (unsigned i = 0; i < NumArgs; i++)
1286 HasDependentArg |= Args[i]->isTypeDependent();
1287
Eli Friedman59c04372009-07-29 19:44:27 +00001288 QualType FieldType = Member->getType();
1289 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1290 FieldType = Array->getElementType();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001291 if (FieldType->isDependentType() || HasDependentArg) {
1292 // Can't check initialization for a member of dependent type or when
1293 // any of the arguments are type-dependent expressions.
1294 OwningExprResult Init
1295 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1296 RParenLoc));
1297
1298 // Erase any temporaries within this evaluation context; we're not
1299 // going to track them in the AST, since we'll be rebuilding the
1300 // ASTs during template instantiation.
1301 ExprTemporaries.erase(
1302 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1303 ExprTemporaries.end());
1304
1305 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1306 LParenLoc,
1307 Init.takeAs<Expr>(),
1308 RParenLoc);
1309
Douglas Gregor7ad83902008-11-05 04:29:56 +00001310 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001311
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001312 if (Member->isInvalidDecl())
1313 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001314
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001315 // Initialize the member.
1316 InitializedEntity MemberEntity =
1317 InitializedEntity::InitializeMember(Member, 0);
1318 InitializationKind Kind =
1319 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1320
1321 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1322
1323 OwningExprResult MemberInit =
1324 InitSeq.Perform(*this, MemberEntity, Kind,
1325 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1326 if (MemberInit.isInvalid())
1327 return true;
1328
1329 // C++0x [class.base.init]p7:
1330 // The initialization of each base and member constitutes a
1331 // full-expression.
1332 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1333 if (MemberInit.isInvalid())
1334 return true;
1335
1336 // If we are in a dependent context, template instantiation will
1337 // perform this type-checking again. Just save the arguments that we
1338 // received in a ParenListExpr.
1339 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1340 // of the information that we have about the member
1341 // initializer. However, deconstructing the ASTs is a dicey process,
1342 // and this approach is far more likely to get the corner cases right.
1343 if (CurContext->isDependentContext()) {
1344 // Bump the reference count of all of the arguments.
1345 for (unsigned I = 0; I != NumArgs; ++I)
1346 Args[I]->Retain();
1347
1348 OwningExprResult Init
1349 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1350 RParenLoc));
1351 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1352 LParenLoc,
1353 Init.takeAs<Expr>(),
1354 RParenLoc);
1355 }
1356
Douglas Gregor802ab452009-12-02 22:36:29 +00001357 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001358 LParenLoc,
1359 MemberInit.takeAs<Expr>(),
1360 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001361}
1362
1363Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001364Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001365 Expr **Args, unsigned NumArgs,
1366 SourceLocation LParenLoc, SourceLocation RParenLoc,
1367 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001368 bool HasDependentArg = false;
1369 for (unsigned i = 0; i < NumArgs; i++)
1370 HasDependentArg |= Args[i]->isTypeDependent();
1371
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001372 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001373 if (BaseType->isDependentType() || HasDependentArg) {
1374 // Can't check initialization for a base of dependent type or when
1375 // any of the arguments are type-dependent expressions.
1376 OwningExprResult BaseInit
1377 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1378 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001379
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001380 // Erase any temporaries within this evaluation context; we're not
1381 // going to track them in the AST, since we'll be rebuilding the
1382 // ASTs during template instantiation.
1383 ExprTemporaries.erase(
1384 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1385 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001387 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001388 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001389 LParenLoc,
1390 BaseInit.takeAs<Expr>(),
1391 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001392 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001393
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001394 if (!BaseType->isRecordType())
1395 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001396 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001397
1398 // C++ [class.base.init]p2:
1399 // [...] Unless the mem-initializer-id names a nonstatic data
1400 // member of the constructor’s class or a direct or virtual base
1401 // of that class, the mem-initializer is ill-formed. A
1402 // mem-initializer-list can initialize a base class using any
1403 // name that denotes that base class type.
1404
1405 // Check for direct and virtual base classes.
1406 const CXXBaseSpecifier *DirectBaseSpec = 0;
1407 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1408 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1409 VirtualBaseSpec);
1410
1411 // C++ [base.class.init]p2:
1412 // If a mem-initializer-id is ambiguous because it designates both
1413 // a direct non-virtual base class and an inherited virtual base
1414 // class, the mem-initializer is ill-formed.
1415 if (DirectBaseSpec && VirtualBaseSpec)
1416 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001417 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001418 // C++ [base.class.init]p2:
1419 // Unless the mem-initializer-id names a nonstatic data membeer of the
1420 // constructor's class ot a direst or virtual base of that class, the
1421 // mem-initializer is ill-formed.
1422 if (!DirectBaseSpec && !VirtualBaseSpec)
1423 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall110acc12010-04-27 01:43:38 +00001424 << BaseType << Context.getTypeDeclType(ClassDecl)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001425 << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001426
1427 CXXBaseSpecifier *BaseSpec
1428 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1429 if (!BaseSpec)
1430 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1431
1432 // Initialize the base.
1433 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001434 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001435 InitializationKind Kind =
1436 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1437
1438 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1439
1440 OwningExprResult BaseInit =
1441 InitSeq.Perform(*this, BaseEntity, Kind,
1442 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1443 if (BaseInit.isInvalid())
1444 return true;
1445
1446 // C++0x [class.base.init]p7:
1447 // The initialization of each base and member constitutes a
1448 // full-expression.
1449 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1450 if (BaseInit.isInvalid())
1451 return true;
1452
1453 // If we are in a dependent context, template instantiation will
1454 // perform this type-checking again. Just save the arguments that we
1455 // received in a ParenListExpr.
1456 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1457 // of the information that we have about the base
1458 // initializer. However, deconstructing the ASTs is a dicey process,
1459 // and this approach is far more likely to get the corner cases right.
1460 if (CurContext->isDependentContext()) {
1461 // Bump the reference count of all of the arguments.
1462 for (unsigned I = 0; I != NumArgs; ++I)
1463 Args[I]->Retain();
1464
1465 OwningExprResult Init
1466 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1467 RParenLoc));
1468 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001469 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001470 LParenLoc,
1471 Init.takeAs<Expr>(),
1472 RParenLoc);
1473 }
1474
1475 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001476 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001477 LParenLoc,
1478 BaseInit.takeAs<Expr>(),
1479 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001480}
1481
Anders Carlssone5ef7402010-04-23 03:10:23 +00001482/// ImplicitInitializerKind - How an implicit base or member initializer should
1483/// initialize its base or member.
1484enum ImplicitInitializerKind {
1485 IIK_Default,
1486 IIK_Copy,
1487 IIK_Move
1488};
1489
Anders Carlssondefefd22010-04-23 02:00:02 +00001490static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001491BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001492 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001493 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001494 bool IsInheritedVirtualBase,
1495 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001496 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001497 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1498 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001499
Anders Carlssone5ef7402010-04-23 03:10:23 +00001500 Sema::OwningExprResult BaseInit(SemaRef);
1501
1502 switch (ImplicitInitKind) {
1503 case IIK_Default: {
1504 InitializationKind InitKind
1505 = InitializationKind::CreateDefault(Constructor->getLocation());
1506 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1507 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1508 Sema::MultiExprArg(SemaRef, 0, 0));
1509 break;
1510 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001511
Anders Carlssone5ef7402010-04-23 03:10:23 +00001512 case IIK_Copy: {
1513 ParmVarDecl *Param = Constructor->getParamDecl(0);
1514 QualType ParamType = Param->getType().getNonReferenceType();
1515
1516 Expr *CopyCtorArg =
1517 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001518 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001519
Anders Carlssonc7957502010-04-24 22:02:54 +00001520 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001521 QualType ArgTy =
1522 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1523 ParamType.getQualifiers());
1524 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonc7957502010-04-24 22:02:54 +00001525 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson8f2abbc2010-04-24 22:54:32 +00001526 /*isLvalue=*/true,
1527 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonc7957502010-04-24 22:02:54 +00001528
Anders Carlssone5ef7402010-04-23 03:10:23 +00001529 InitializationKind InitKind
1530 = InitializationKind::CreateDirect(Constructor->getLocation(),
1531 SourceLocation(), SourceLocation());
1532 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1533 &CopyCtorArg, 1);
1534 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1535 Sema::MultiExprArg(SemaRef,
1536 (void**)&CopyCtorArg, 1));
1537 break;
1538 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001539
Anders Carlssone5ef7402010-04-23 03:10:23 +00001540 case IIK_Move:
1541 assert(false && "Unhandled initializer kind!");
1542 }
1543
Anders Carlsson84688f22010-04-20 23:11:20 +00001544 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1545 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001546 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001547
Anders Carlssondefefd22010-04-23 02:00:02 +00001548 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001549 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1550 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1551 SourceLocation()),
1552 BaseSpec->isVirtual(),
1553 SourceLocation(),
1554 BaseInit.takeAs<Expr>(),
1555 SourceLocation());
1556
Anders Carlssondefefd22010-04-23 02:00:02 +00001557 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001558}
1559
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001560static bool
1561BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001562 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001563 FieldDecl *Field,
1564 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001565 if (ImplicitInitKind == IIK_Copy) {
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001566 SourceLocation Loc = Constructor->getLocation();
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001567 ParmVarDecl *Param = Constructor->getParamDecl(0);
1568 QualType ParamType = Param->getType().getNonReferenceType();
1569
1570 Expr *MemberExprBase =
1571 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001572 Loc, ParamType, 0);
1573
1574 // Build a reference to this field within the parameter.
1575 CXXScopeSpec SS;
1576 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1577 Sema::LookupMemberName);
1578 MemberLookup.addDecl(Field, AS_public);
1579 MemberLookup.resolveKind();
1580 Sema::OwningExprResult CopyCtorArg
1581 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1582 ParamType, Loc,
1583 /*IsArrow=*/false,
1584 SS,
1585 /*FirstQualifierInScope=*/0,
1586 MemberLookup,
1587 /*TemplateArgs=*/0);
1588 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001589 return true;
1590
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001591 // When the field we are copying is an array, create index variables for
1592 // each dimension of the array. We use these index variables to subscript
1593 // the source array, and other clients (e.g., CodeGen) will perform the
1594 // necessary iteration with these index variables.
1595 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1596 QualType BaseType = Field->getType();
1597 QualType SizeType = SemaRef.Context.getSizeType();
1598 while (const ConstantArrayType *Array
1599 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1600 // Create the iteration variable for this array index.
1601 IdentifierInfo *IterationVarName = 0;
1602 {
1603 llvm::SmallString<8> Str;
1604 llvm::raw_svector_ostream OS(Str);
1605 OS << "__i" << IndexVariables.size();
1606 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1607 }
1608 VarDecl *IterationVar
1609 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1610 IterationVarName, SizeType,
1611 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1612 VarDecl::None, VarDecl::None);
1613 IndexVariables.push_back(IterationVar);
1614
1615 // Create a reference to the iteration variable.
1616 Sema::OwningExprResult IterationVarRef
1617 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1618 assert(!IterationVarRef.isInvalid() &&
1619 "Reference to invented variable cannot fail!");
1620
1621 // Subscript the array with this iteration variable.
1622 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1623 Loc,
1624 move(IterationVarRef),
1625 Loc);
1626 if (CopyCtorArg.isInvalid())
1627 return true;
1628
1629 BaseType = Array->getElementType();
1630 }
1631
1632 // Construct the entity that we will be initializing. For an array, this
1633 // will be first element in the array, which may require several levels
1634 // of array-subscript entities.
1635 llvm::SmallVector<InitializedEntity, 4> Entities;
1636 Entities.reserve(1 + IndexVariables.size());
1637 Entities.push_back(InitializedEntity::InitializeMember(Field));
1638 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1639 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1640 0,
1641 Entities.back()));
1642
1643 // Direct-initialize to use the copy constructor.
1644 InitializationKind InitKind =
1645 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1646
1647 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1648 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1649 &CopyCtorArgE, 1);
1650
1651 Sema::OwningExprResult MemberInit
1652 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1653 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1654 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1655 if (MemberInit.isInvalid())
1656 return true;
1657
1658 CXXMemberInit
1659 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1660 MemberInit.takeAs<Expr>(), Loc,
1661 IndexVariables.data(),
1662 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001663 return false;
1664 }
1665
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001666 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1667
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001668 QualType FieldBaseElementType =
1669 SemaRef.Context.getBaseElementType(Field->getType());
1670
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001671 if (FieldBaseElementType->isRecordType()) {
1672 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001673 InitializationKind InitKind =
1674 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001675
1676 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1677 Sema::OwningExprResult MemberInit =
1678 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1679 Sema::MultiExprArg(SemaRef, 0, 0));
1680 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1681 if (MemberInit.isInvalid())
1682 return true;
1683
1684 CXXMemberInit =
1685 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1686 Field, SourceLocation(),
1687 SourceLocation(),
1688 MemberInit.takeAs<Expr>(),
1689 SourceLocation());
1690 return false;
1691 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001692
1693 if (FieldBaseElementType->isReferenceType()) {
1694 SemaRef.Diag(Constructor->getLocation(),
1695 diag::err_uninitialized_member_in_ctor)
1696 << (int)Constructor->isImplicit()
1697 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1698 << 0 << Field->getDeclName();
1699 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1700 return true;
1701 }
1702
1703 if (FieldBaseElementType.isConstQualified()) {
1704 SemaRef.Diag(Constructor->getLocation(),
1705 diag::err_uninitialized_member_in_ctor)
1706 << (int)Constructor->isImplicit()
1707 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1708 << 1 << Field->getDeclName();
1709 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1710 return true;
1711 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001712
1713 // Nothing to initialize.
1714 CXXMemberInit = 0;
1715 return false;
1716}
1717
Eli Friedman80c30da2009-11-09 19:20:36 +00001718bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001719Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001720 CXXBaseOrMemberInitializer **Initializers,
1721 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001722 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001723 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001724 // Just store the initializers as written, they will be checked during
1725 // instantiation.
1726 if (NumInitializers > 0) {
1727 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1728 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1729 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1730 memcpy(baseOrMemberInitializers, Initializers,
1731 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1732 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1733 }
1734
1735 return false;
1736 }
1737
Anders Carlssone5ef7402010-04-23 03:10:23 +00001738 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1739
1740 // FIXME: Handle implicit move constructors.
1741 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1742 ImplicitInitKind = IIK_Copy;
1743
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001744 // We need to build the initializer AST according to order of construction
1745 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001746 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001747 if (!ClassDecl)
1748 return true;
1749
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001750 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1751 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman80c30da2009-11-09 19:20:36 +00001752 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001754 for (unsigned i = 0; i < NumInitializers; i++) {
1755 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001756
1757 if (Member->isBaseInitializer())
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001758 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001759 else
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001760 AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001761 }
1762
Anders Carlsson711f34a2010-04-21 19:52:01 +00001763 // Keep track of the direct virtual bases.
1764 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1765 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1766 E = ClassDecl->bases_end(); I != E; ++I) {
1767 if (I->isVirtual())
1768 DirectVBases.insert(I);
1769 }
1770
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001771 // Push virtual bases before others.
1772 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1773 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1774
1775 if (CXXBaseOrMemberInitializer *Value
1776 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1777 AllToInit.push_back(Value);
1778 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001779 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001780 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001781 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1782 VBase, IsInheritedVirtualBase,
1783 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001784 HadError = true;
1785 continue;
1786 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001787
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001788 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001789 }
1790 }
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1793 E = ClassDecl->bases_end(); Base != E; ++Base) {
1794 // Virtuals are in the virtual base list and already constructed.
1795 if (Base->isVirtual())
1796 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001798 if (CXXBaseOrMemberInitializer *Value
1799 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1800 AllToInit.push_back(Value);
1801 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001802 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001803 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1804 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001805 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001806 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001807 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001808 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001809
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001810 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001811 }
1812 }
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001814 // non-static data members.
1815 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1816 E = ClassDecl->field_end(); Field != E; ++Field) {
1817 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001818 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001819 Field->getType()->getAs<RecordType>()) {
1820 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001821 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001822 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001823 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1824 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1825 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1826 // set to the anonymous union data member used in the initializer
1827 // list.
1828 Value->setMember(*Field);
1829 Value->setAnonUnionMember(*FA);
1830 AllToInit.push_back(Value);
1831 break;
1832 }
1833 }
1834 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001835
1836 if (ImplicitInitKind == IIK_Default)
1837 continue;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001838 }
1839 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1840 AllToInit.push_back(Value);
1841 continue;
1842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Anders Carlssondefefd22010-04-23 02:00:02 +00001844 if (AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001845 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001846
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001847 CXXBaseOrMemberInitializer *Member;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001848 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1849 *Field, Member)) {
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001850 HadError = true;
1851 continue;
1852 }
1853
1854 // If the member doesn't need to be initialized, it will be null.
1855 if (Member)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001856 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001859 NumInitializers = AllToInit.size();
1860 if (NumInitializers > 0) {
1861 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1862 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1863 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallef027fe2010-03-16 21:39:52 +00001864 memcpy(baseOrMemberInitializers, AllToInit.data(),
1865 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001866 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001867
John McCallef027fe2010-03-16 21:39:52 +00001868 // Constructors implicitly reference the base and member
1869 // destructors.
1870 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1871 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001872 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001873
1874 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001875}
1876
Eli Friedman6347f422009-07-21 19:28:10 +00001877static void *GetKeyForTopLevelField(FieldDecl *Field) {
1878 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001879 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001880 if (RT->getDecl()->isAnonymousStructOrUnion())
1881 return static_cast<void *>(RT->getDecl());
1882 }
1883 return static_cast<void *>(Field);
1884}
1885
Anders Carlssonea356fb2010-04-02 05:42:15 +00001886static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1887 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001888}
1889
Anders Carlssonea356fb2010-04-02 05:42:15 +00001890static void *GetKeyForMember(ASTContext &Context,
1891 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001892 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001893 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001894 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001895
Eli Friedman6347f422009-07-21 19:28:10 +00001896 // For fields injected into the class via declaration of an anonymous union,
1897 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001898 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001900 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1901 // data member of the class. Data member used in the initializer list is
1902 // in AnonUnionMember field.
1903 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1904 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001905
John McCall3c3ccdb2010-04-10 09:28:51 +00001906 // If the field is a member of an anonymous struct or union, our key
1907 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001908 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001909 if (RD->isAnonymousStructOrUnion()) {
1910 while (true) {
1911 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1912 if (Parent->isAnonymousStructOrUnion())
1913 RD = Parent;
1914 else
1915 break;
1916 }
1917
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001918 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001919 }
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001921 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001922}
1923
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001924static void
1925DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001926 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001927 CXXBaseOrMemberInitializer **Inits,
1928 unsigned NumInits) {
1929 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001930 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001931
John McCalld6ca8da2010-04-10 07:37:23 +00001932 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1933 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001934 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001935
John McCalld6ca8da2010-04-10 07:37:23 +00001936 // Build the list of bases and members in the order that they'll
1937 // actually be initialized. The explicit initializers should be in
1938 // this same order but may be missing things.
1939 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Anders Carlsson071d6102010-04-02 03:38:04 +00001941 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1942
John McCalld6ca8da2010-04-10 07:37:23 +00001943 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001944 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001945 ClassDecl->vbases_begin(),
1946 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00001947 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001948
John McCalld6ca8da2010-04-10 07:37:23 +00001949 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001950 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001951 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001952 if (Base->isVirtual())
1953 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00001954 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001955 }
Mike Stump1eb44332009-09-09 15:08:12 +00001956
John McCalld6ca8da2010-04-10 07:37:23 +00001957 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001958 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1959 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00001960 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001961
John McCalld6ca8da2010-04-10 07:37:23 +00001962 unsigned NumIdealInits = IdealInitKeys.size();
1963 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00001964
John McCalld6ca8da2010-04-10 07:37:23 +00001965 CXXBaseOrMemberInitializer *PrevInit = 0;
1966 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1967 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1968 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1969
1970 // Scan forward to try to find this initializer in the idealized
1971 // initializers list.
1972 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1973 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001974 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001975
1976 // If we didn't find this initializer, it must be because we
1977 // scanned past it on a previous iteration. That can only
1978 // happen if we're out of order; emit a warning.
1979 if (IdealIndex == NumIdealInits) {
1980 assert(PrevInit && "initializer not found in initializer list");
1981
1982 Sema::SemaDiagnosticBuilder D =
1983 SemaRef.Diag(PrevInit->getSourceLocation(),
1984 diag::warn_initializer_out_of_order);
1985
1986 if (PrevInit->isMemberInitializer())
1987 D << 0 << PrevInit->getMember()->getDeclName();
1988 else
1989 D << 1 << PrevInit->getBaseClassInfo()->getType();
1990
1991 if (Init->isMemberInitializer())
1992 D << 0 << Init->getMember()->getDeclName();
1993 else
1994 D << 1 << Init->getBaseClassInfo()->getType();
1995
1996 // Move back to the initializer's location in the ideal list.
1997 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1998 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001999 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002000
2001 assert(IdealIndex != NumIdealInits &&
2002 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002003 }
John McCalld6ca8da2010-04-10 07:37:23 +00002004
2005 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002006 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002007}
2008
John McCall3c3ccdb2010-04-10 09:28:51 +00002009namespace {
2010bool CheckRedundantInit(Sema &S,
2011 CXXBaseOrMemberInitializer *Init,
2012 CXXBaseOrMemberInitializer *&PrevInit) {
2013 if (!PrevInit) {
2014 PrevInit = Init;
2015 return false;
2016 }
2017
2018 if (FieldDecl *Field = Init->getMember())
2019 S.Diag(Init->getSourceLocation(),
2020 diag::err_multiple_mem_initialization)
2021 << Field->getDeclName()
2022 << Init->getSourceRange();
2023 else {
2024 Type *BaseClass = Init->getBaseClass();
2025 assert(BaseClass && "neither field nor base");
2026 S.Diag(Init->getSourceLocation(),
2027 diag::err_multiple_base_initialization)
2028 << QualType(BaseClass, 0)
2029 << Init->getSourceRange();
2030 }
2031 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2032 << 0 << PrevInit->getSourceRange();
2033
2034 return true;
2035}
2036
2037typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2038typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2039
2040bool CheckRedundantUnionInit(Sema &S,
2041 CXXBaseOrMemberInitializer *Init,
2042 RedundantUnionMap &Unions) {
2043 FieldDecl *Field = Init->getMember();
2044 RecordDecl *Parent = Field->getParent();
2045 if (!Parent->isAnonymousStructOrUnion())
2046 return false;
2047
2048 NamedDecl *Child = Field;
2049 do {
2050 if (Parent->isUnion()) {
2051 UnionEntry &En = Unions[Parent];
2052 if (En.first && En.first != Child) {
2053 S.Diag(Init->getSourceLocation(),
2054 diag::err_multiple_mem_union_initialization)
2055 << Field->getDeclName()
2056 << Init->getSourceRange();
2057 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2058 << 0 << En.second->getSourceRange();
2059 return true;
2060 } else if (!En.first) {
2061 En.first = Child;
2062 En.second = Init;
2063 }
2064 }
2065
2066 Child = Parent;
2067 Parent = cast<RecordDecl>(Parent->getDeclContext());
2068 } while (Parent->isAnonymousStructOrUnion());
2069
2070 return false;
2071}
2072}
2073
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002074/// ActOnMemInitializers - Handle the member initializers for a constructor.
2075void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2076 SourceLocation ColonLoc,
2077 MemInitTy **meminits, unsigned NumMemInits,
2078 bool AnyErrors) {
2079 if (!ConstructorDecl)
2080 return;
2081
2082 AdjustDeclIfTemplate(ConstructorDecl);
2083
2084 CXXConstructorDecl *Constructor
2085 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2086
2087 if (!Constructor) {
2088 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2089 return;
2090 }
2091
2092 CXXBaseOrMemberInitializer **MemInits =
2093 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002094
2095 // Mapping for the duplicate initializers check.
2096 // For member initializers, this is keyed with a FieldDecl*.
2097 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002098 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002099
2100 // Mapping for the inconsistent anonymous-union initializers check.
2101 RedundantUnionMap MemberUnions;
2102
Anders Carlssonea356fb2010-04-02 05:42:15 +00002103 bool HadError = false;
2104 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002105 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002106
John McCall3c3ccdb2010-04-10 09:28:51 +00002107 if (Init->isMemberInitializer()) {
2108 FieldDecl *Field = Init->getMember();
2109 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2110 CheckRedundantUnionInit(*this, Init, MemberUnions))
2111 HadError = true;
2112 } else {
2113 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2114 if (CheckRedundantInit(*this, Init, Members[Key]))
2115 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002116 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002117 }
2118
Anders Carlssonea356fb2010-04-02 05:42:15 +00002119 if (HadError)
2120 return;
2121
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002122 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002123
2124 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002125}
2126
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002127void
John McCallef027fe2010-03-16 21:39:52 +00002128Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2129 CXXRecordDecl *ClassDecl) {
2130 // Ignore dependent contexts.
2131 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002132 return;
John McCall58e6f342010-03-16 05:22:47 +00002133
2134 // FIXME: all the access-control diagnostics are positioned on the
2135 // field/base declaration. That's probably good; that said, the
2136 // user might reasonably want to know why the destructor is being
2137 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002138
Anders Carlsson9f853df2009-11-17 04:44:12 +00002139 // Non-static data members.
2140 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2141 E = ClassDecl->field_end(); I != E; ++I) {
2142 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002143 if (Field->isInvalidDecl())
2144 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002145 QualType FieldType = Context.getBaseElementType(Field->getType());
2146
2147 const RecordType* RT = FieldType->getAs<RecordType>();
2148 if (!RT)
2149 continue;
2150
2151 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2152 if (FieldClassDecl->hasTrivialDestructor())
2153 continue;
2154
John McCall58e6f342010-03-16 05:22:47 +00002155 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2156 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002157 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002158 << Field->getDeclName()
2159 << FieldType);
2160
John McCallef027fe2010-03-16 21:39:52 +00002161 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002162 }
2163
John McCall58e6f342010-03-16 05:22:47 +00002164 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2165
Anders Carlsson9f853df2009-11-17 04:44:12 +00002166 // Bases.
2167 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2168 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002169 // Bases are always records in a well-formed non-dependent class.
2170 const RecordType *RT = Base->getType()->getAs<RecordType>();
2171
2172 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002173 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002174 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002175
2176 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002177 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002178 if (BaseClassDecl->hasTrivialDestructor())
2179 continue;
John McCall58e6f342010-03-16 05:22:47 +00002180
2181 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2182
2183 // FIXME: caret should be on the start of the class name
2184 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002185 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002186 << Base->getType()
2187 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002188
John McCallef027fe2010-03-16 21:39:52 +00002189 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002190 }
2191
2192 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002193 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2194 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002195
2196 // Bases are always records in a well-formed non-dependent class.
2197 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2198
2199 // Ignore direct virtual bases.
2200 if (DirectVirtualBases.count(RT))
2201 continue;
2202
Anders Carlsson9f853df2009-11-17 04:44:12 +00002203 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002204 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002205 if (BaseClassDecl->hasTrivialDestructor())
2206 continue;
John McCall58e6f342010-03-16 05:22:47 +00002207
2208 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2209 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002210 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002211 << VBase->getType());
2212
John McCallef027fe2010-03-16 21:39:52 +00002213 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002214 }
2215}
2216
Fariborz Jahanian393612e2009-07-21 22:36:06 +00002217void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002218 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002219 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Mike Stump1eb44332009-09-09 15:08:12 +00002221 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00002222 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002223 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002224}
2225
Mike Stump1eb44332009-09-09 15:08:12 +00002226bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002227 unsigned DiagID, AbstractDiagSelID SelID,
2228 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002229 if (SelID == -1)
2230 return RequireNonAbstractType(Loc, T,
2231 PDiag(DiagID), CurrentRD);
2232 else
2233 return RequireNonAbstractType(Loc, T,
2234 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002235}
2236
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002237bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2238 const PartialDiagnostic &PD,
2239 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002240 if (!getLangOptions().CPlusPlus)
2241 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Anders Carlsson11f21a02009-03-23 19:10:31 +00002243 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002244 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002245 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Ted Kremenek6217b802009-07-29 21:53:49 +00002247 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002248 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002249 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002250 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002252 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002253 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002254 }
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Ted Kremenek6217b802009-07-29 21:53:49 +00002256 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002257 if (!RT)
2258 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002259
John McCall86ff3082010-02-04 22:26:26 +00002260 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002261
Anders Carlssone65a3c82009-03-24 17:23:42 +00002262 if (CurrentRD && CurrentRD != RD)
2263 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002264
John McCall86ff3082010-02-04 22:26:26 +00002265 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002266 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002267 return false;
2268
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002269 if (!RD->isAbstract())
2270 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002272 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002274 // Check if we've already emitted the list of pure virtual functions for this
2275 // class.
2276 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2277 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002279 CXXFinalOverriderMap FinalOverriders;
2280 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002282 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2283 MEnd = FinalOverriders.end();
2284 M != MEnd;
2285 ++M) {
2286 for (OverridingMethods::iterator SO = M->second.begin(),
2287 SOEnd = M->second.end();
2288 SO != SOEnd; ++SO) {
2289 // C++ [class.abstract]p4:
2290 // A class is abstract if it contains or inherits at least one
2291 // pure virtual function for which the final overrider is pure
2292 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002294 //
2295 if (SO->second.size() != 1)
2296 continue;
2297
2298 if (!SO->second.front().Method->isPure())
2299 continue;
2300
2301 Diag(SO->second.front().Method->getLocation(),
2302 diag::note_pure_virtual_function)
2303 << SO->second.front().Method->getDeclName();
2304 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002305 }
2306
2307 if (!PureVirtualClassDiagSet)
2308 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2309 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002311 return true;
2312}
2313
Anders Carlsson8211eff2009-03-24 01:19:16 +00002314namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002315 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002316 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2317 Sema &SemaRef;
2318 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Anders Carlssone65a3c82009-03-24 17:23:42 +00002320 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002321 bool Invalid = false;
2322
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002323 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2324 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002325 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002326
Anders Carlsson8211eff2009-03-24 01:19:16 +00002327 return Invalid;
2328 }
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Anders Carlssone65a3c82009-03-24 17:23:42 +00002330 public:
2331 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2332 : SemaRef(SemaRef), AbstractClass(ac) {
2333 Visit(SemaRef.Context.getTranslationUnitDecl());
2334 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002335
Anders Carlssone65a3c82009-03-24 17:23:42 +00002336 bool VisitFunctionDecl(const FunctionDecl *FD) {
2337 if (FD->isThisDeclarationADefinition()) {
2338 // No need to do the check if we're in a definition, because it requires
2339 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002340 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002341 return VisitDeclContext(FD);
2342 }
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Anders Carlssone65a3c82009-03-24 17:23:42 +00002344 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002345 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002346 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002347 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2348 diag::err_abstract_type_in_decl,
2349 Sema::AbstractReturnType,
2350 AbstractClass);
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002353 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002354 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002355 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002356 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002357 VD->getOriginalType(),
2358 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002359 Sema::AbstractParamType,
2360 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002361 }
2362
2363 return Invalid;
2364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Anders Carlssone65a3c82009-03-24 17:23:42 +00002366 bool VisitDecl(const Decl* D) {
2367 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2368 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Anders Carlssone65a3c82009-03-24 17:23:42 +00002370 return false;
2371 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002372 };
2373}
2374
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002375/// \brief Perform semantic checks on a class definition that has been
2376/// completing, introducing implicitly-declared members, checking for
2377/// abstract types, etc.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002378void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002379 if (!Record || Record->isInvalidDecl())
2380 return;
2381
Eli Friedmanff2d8782009-12-16 20:00:27 +00002382 if (!Record->isDependentType())
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002383 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002384
Eli Friedmanff2d8782009-12-16 20:00:27 +00002385 if (Record->isInvalidDecl())
2386 return;
2387
John McCall233a6412010-01-28 07:38:46 +00002388 // Set access bits correctly on the directly-declared conversions.
2389 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2390 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2391 Convs->setAccess(I, (*I)->getAccess());
2392
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002393 // Determine whether we need to check for final overriders. We do
2394 // this either when there are virtual base classes (in which case we
2395 // may end up finding multiple final overriders for a given virtual
2396 // function) or any of the base classes is abstract (in which case
2397 // we might detect that this class is abstract).
2398 bool CheckFinalOverriders = false;
2399 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2400 !Record->isDependentType()) {
2401 if (Record->getNumVBases())
2402 CheckFinalOverriders = true;
2403 else if (!Record->isAbstract()) {
2404 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2405 BEnd = Record->bases_end();
2406 B != BEnd; ++B) {
2407 CXXRecordDecl *BaseDecl
2408 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2409 if (BaseDecl->isAbstract()) {
2410 CheckFinalOverriders = true;
2411 break;
2412 }
2413 }
2414 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002415 }
2416
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002417 if (CheckFinalOverriders) {
2418 CXXFinalOverriderMap FinalOverriders;
2419 Record->getFinalOverriders(FinalOverriders);
2420
2421 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2422 MEnd = FinalOverriders.end();
2423 M != MEnd; ++M) {
2424 for (OverridingMethods::iterator SO = M->second.begin(),
2425 SOEnd = M->second.end();
2426 SO != SOEnd; ++SO) {
2427 assert(SO->second.size() > 0 &&
2428 "All virtual functions have overridding virtual functions");
2429 if (SO->second.size() == 1) {
2430 // C++ [class.abstract]p4:
2431 // A class is abstract if it contains or inherits at least one
2432 // pure virtual function for which the final overrider is pure
2433 // virtual.
2434 if (SO->second.front().Method->isPure())
2435 Record->setAbstract(true);
2436 continue;
2437 }
2438
2439 // C++ [class.virtual]p2:
2440 // In a derived class, if a virtual member function of a base
2441 // class subobject has more than one final overrider the
2442 // program is ill-formed.
2443 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2444 << (NamedDecl *)M->first << Record;
2445 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2446 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2447 OMEnd = SO->second.end();
2448 OM != OMEnd; ++OM)
2449 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2450 << (NamedDecl *)M->first << OM->Method->getParent();
2451
2452 Record->setInvalidDecl();
2453 }
2454 }
2455 }
2456
2457 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002458 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor325e5932010-04-15 00:00:53 +00002459
2460 // If this is not an aggregate type and has no user-declared constructor,
2461 // complain about any non-static data members of reference or const scalar
2462 // type, since they will never get initializers.
2463 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2464 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2465 bool Complained = false;
2466 for (RecordDecl::field_iterator F = Record->field_begin(),
2467 FEnd = Record->field_end();
2468 F != FEnd; ++F) {
2469 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002470 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002471 if (!Complained) {
2472 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2473 << Record->getTagKind() << Record;
2474 Complained = true;
2475 }
2476
2477 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2478 << F->getType()->isReferenceType()
2479 << F->getDeclName();
2480 }
2481 }
2482 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002483
2484 if (Record->isDynamicClass())
2485 DynamicClasses.push_back(Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002486}
2487
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002488void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002489 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002490 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002491 SourceLocation RBrac,
2492 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002493 if (!TagDecl)
2494 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Douglas Gregor42af25f2009-05-11 19:58:34 +00002496 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002497
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002498 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002499 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002500 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002501
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002502 CheckCompletedCXXClass(S,
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002503 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002504}
2505
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002506/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2507/// special functions, such as the default constructor, copy
2508/// constructor, or destructor, to the given C++ class (C++
2509/// [special]p1). This routine can only be executed just before the
2510/// definition of the class is complete.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002511///
2512/// The scope, if provided, is the class scope.
2513void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2514 CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002515 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002516 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002517
Sebastian Redl465226e2009-05-27 22:11:52 +00002518 // FIXME: Implicit declarations have exception specifications, which are
2519 // the union of the specifications of the implicitly called functions.
2520
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002521 if (!ClassDecl->hasUserDeclaredConstructor()) {
2522 // C++ [class.ctor]p5:
2523 // A default constructor for a class X is a constructor of class X
2524 // that can be called without an argument. If there is no
2525 // user-declared constructor for class X, a default constructor is
2526 // implicitly declared. An implicitly-declared default constructor
2527 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002528 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002529 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002530 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002531 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002532 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002533 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002534 0, 0, false, 0,
2535 /*FIXME*/false, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002536 0, 0,
2537 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002538 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002539 /*isExplicit=*/false,
2540 /*isInline=*/true,
2541 /*isImplicitlyDeclared=*/true);
2542 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002543 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002544 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002545 if (S)
2546 PushOnScopeChains(DefaultCon, S, true);
2547 else
2548 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002549 }
2550
2551 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2552 // C++ [class.copy]p4:
2553 // If the class definition does not explicitly declare a copy
2554 // constructor, one is declared implicitly.
2555
2556 // C++ [class.copy]p5:
2557 // The implicitly-declared copy constructor for a class X will
2558 // have the form
2559 //
2560 // X::X(const X&)
2561 //
2562 // if
2563 bool HasConstCopyConstructor = true;
2564
2565 // -- each direct or virtual base class B of X has a copy
2566 // constructor whose first parameter is of type const B& or
2567 // const volatile B&, and
2568 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2569 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2570 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002571 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002572 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002573 = BaseClassDecl->hasConstCopyConstructor(Context);
2574 }
2575
2576 // -- for all the nonstatic data members of X that are of a
2577 // class type M (or array thereof), each such class type
2578 // has a copy constructor whose first parameter is of type
2579 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002580 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2581 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002582 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002583 QualType FieldType = (*Field)->getType();
2584 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2585 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002586 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002587 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002588 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002589 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002590 = FieldClassDecl->hasConstCopyConstructor(Context);
2591 }
2592 }
2593
Sebastian Redl64b45f72009-01-05 20:52:13 +00002594 // Otherwise, the implicitly declared copy constructor will have
2595 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002596 //
2597 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002598 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002599 if (HasConstCopyConstructor)
2600 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002601 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002602
Sebastian Redl64b45f72009-01-05 20:52:13 +00002603 // An implicitly-declared copy constructor is an inline public
2604 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002605 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002606 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002607 CXXConstructorDecl *CopyConstructor
2608 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002609 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002610 Context.getFunctionType(Context.VoidTy,
2611 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002612 false, 0,
Chris Lattnerface9812010-05-12 23:26:21 +00002613 /*FIXME: hasExceptionSpec*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002614 false, 0, 0,
2615 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002616 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002617 /*isExplicit=*/false,
2618 /*isInline=*/true,
2619 /*isImplicitlyDeclared=*/true);
2620 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002621 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002622 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002623
2624 // Add the parameter to the constructor.
2625 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2626 ClassDecl->getLocation(),
2627 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002628 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002629 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002630 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002631 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002632 if (S)
2633 PushOnScopeChains(CopyConstructor, S, true);
2634 else
2635 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002636 }
2637
Sebastian Redl64b45f72009-01-05 20:52:13 +00002638 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2639 // Note: The following rules are largely analoguous to the copy
2640 // constructor rules. Note that virtual bases are not taken into account
2641 // for determining the argument type of the operator. Note also that
2642 // operators taking an object instead of a reference are allowed.
2643 //
2644 // C++ [class.copy]p10:
2645 // If the class definition does not explicitly declare a copy
2646 // assignment operator, one is declared implicitly.
2647 // The implicitly-defined copy assignment operator for a class X
2648 // will have the form
2649 //
2650 // X& X::operator=(const X&)
2651 //
2652 // if
2653 bool HasConstCopyAssignment = true;
2654
2655 // -- each direct base class B of X has a copy assignment operator
2656 // whose parameter is of type const B&, const volatile B& or B,
2657 // and
2658 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2659 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002660 assert(!Base->getType()->isDependentType() &&
2661 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002662 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002663 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002664 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002665 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002666 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002667 }
2668
2669 // -- for all the nonstatic data members of X that are of a class
2670 // type M (or array thereof), each such class type has a copy
2671 // assignment operator whose parameter is of type const M&,
2672 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002673 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2674 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002675 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002676 QualType FieldType = (*Field)->getType();
2677 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2678 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002679 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002680 const CXXRecordDecl *FieldClassDecl
2681 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002682 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002683 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002684 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002685 }
2686 }
2687
2688 // Otherwise, the implicitly declared copy assignment operator will
2689 // have the form
2690 //
2691 // X& X::operator=(X&)
2692 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002693 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002694 if (HasConstCopyAssignment)
2695 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002696 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002697
2698 // An implicitly-declared copy assignment operator is an inline public
2699 // member of its class.
2700 DeclarationName Name =
2701 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2702 CXXMethodDecl *CopyAssignment =
2703 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2704 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002705 false, 0,
Chris Lattnerface9812010-05-12 23:26:21 +00002706 /*FIXME: hasExceptionSpec*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002707 false, 0, 0,
2708 FunctionType::ExtInfo()),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002709 /*TInfo=*/0, /*isStatic=*/false,
2710 /*StorageClassAsWritten=*/FunctionDecl::None,
2711 /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002712 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002713 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002714 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002715 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002716
2717 // Add the parameter to the operator.
2718 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2719 ClassDecl->getLocation(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00002720 /*Id=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002721 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002722 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002723 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002724 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002725
2726 // Don't call addedAssignmentOperator. There is no way to distinguish an
2727 // implicit from an explicit assignment operator.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002728 if (S)
2729 PushOnScopeChains(CopyAssignment, S, true);
2730 else
2731 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002732 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002733 }
2734
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002735 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002736 // C++ [class.dtor]p2:
2737 // If a class has no user-declared destructor, a destructor is
2738 // declared implicitly. An implicitly-declared destructor is an
2739 // inline public member of its class.
John McCall21ef0fa2010-03-11 09:03:00 +00002740 QualType Ty = Context.getFunctionType(Context.VoidTy,
2741 0, 0, false, 0,
Chris Lattnerface9812010-05-12 23:26:21 +00002742 /*FIXME: hasExceptionSpec*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002743 false, 0, 0, FunctionType::ExtInfo());
John McCall21ef0fa2010-03-11 09:03:00 +00002744
Mike Stump1eb44332009-09-09 15:08:12 +00002745 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002746 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002747 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002748 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall21ef0fa2010-03-11 09:03:00 +00002749 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002750 /*isInline=*/true,
2751 /*isImplicitlyDeclared=*/true);
2752 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002753 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002754 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002755 if (S)
2756 PushOnScopeChains(Destructor, S, true);
2757 else
2758 ClassDecl->addDecl(Destructor);
John McCall21ef0fa2010-03-11 09:03:00 +00002759
2760 // This could be uniqued if it ever proves significant.
2761 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlssond5a942b2009-11-26 21:25:09 +00002762
2763 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002764 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002765}
2766
Douglas Gregor6569d682009-05-27 23:11:45 +00002767void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002768 Decl *D = TemplateD.getAs<Decl>();
2769 if (!D)
2770 return;
2771
2772 TemplateParameterList *Params = 0;
2773 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2774 Params = Template->getTemplateParameters();
2775 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2776 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2777 Params = PartialSpec->getTemplateParameters();
2778 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002779 return;
2780
Douglas Gregor6569d682009-05-27 23:11:45 +00002781 for (TemplateParameterList::iterator Param = Params->begin(),
2782 ParamEnd = Params->end();
2783 Param != ParamEnd; ++Param) {
2784 NamedDecl *Named = cast<NamedDecl>(*Param);
2785 if (Named->getDeclName()) {
2786 S->AddDecl(DeclPtrTy::make(Named));
2787 IdResolver.AddDecl(Named);
2788 }
2789 }
2790}
2791
John McCall7a1dc562009-12-19 10:49:29 +00002792void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2793 if (!RecordD) return;
2794 AdjustDeclIfTemplate(RecordD);
2795 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2796 PushDeclContext(S, Record);
2797}
2798
2799void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2800 if (!RecordD) return;
2801 PopDeclContext();
2802}
2803
Douglas Gregor72b505b2008-12-16 21:30:33 +00002804/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2805/// parsing a top-level (non-nested) C++ class, and we are now
2806/// parsing those parts of the given Method declaration that could
2807/// not be parsed earlier (C++ [class.mem]p2), such as default
2808/// arguments. This action should enter the scope of the given
2809/// Method declaration as if we had just parsed the qualified method
2810/// name. However, it should not bring the parameters into scope;
2811/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002812void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002813}
2814
2815/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2816/// C++ method declaration. We're (re-)introducing the given
2817/// function parameter into scope for use in parsing later parts of
2818/// the method declaration. For example, we could see an
2819/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002820void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002821 if (!ParamD)
2822 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Chris Lattnerb28317a2009-03-28 19:18:32 +00002824 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002825
2826 // If this parameter has an unparsed default argument, clear it out
2827 // to make way for the parsed default argument.
2828 if (Param->hasUnparsedDefaultArg())
2829 Param->setDefaultArg(0);
2830
Chris Lattnerb28317a2009-03-28 19:18:32 +00002831 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002832 if (Param->getDeclName())
2833 IdResolver.AddDecl(Param);
2834}
2835
2836/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2837/// processing the delayed method declaration for Method. The method
2838/// declaration is now considered finished. There may be a separate
2839/// ActOnStartOfFunctionDef action later (not necessarily
2840/// immediately!) for this method, if it was also defined inside the
2841/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002842void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002843 if (!MethodD)
2844 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002846 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002847
Chris Lattnerb28317a2009-03-28 19:18:32 +00002848 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002849
2850 // Now that we have our default arguments, check the constructor
2851 // again. It could produce additional diagnostics or affect whether
2852 // the class has implicitly-declared destructors, among other
2853 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2855 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002856
2857 // Check the default arguments, which we may have added.
2858 if (!Method->isInvalidDecl())
2859 CheckCXXDefaultArguments(Method);
2860}
2861
Douglas Gregor42a552f2008-11-05 20:51:48 +00002862/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002863/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002864/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002865/// emit diagnostics and set the invalid bit to true. In any case, the type
2866/// will be updated to reflect a well-formed type for the constructor and
2867/// returned.
2868QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2869 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002870 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002871
2872 // C++ [class.ctor]p3:
2873 // A constructor shall not be virtual (10.3) or static (9.4). A
2874 // constructor can be invoked for a const, volatile or const
2875 // volatile object. A constructor shall not be declared const,
2876 // volatile, or const volatile (9.3.2).
2877 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002878 if (!D.isInvalidType())
2879 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2880 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2881 << SourceRange(D.getIdentifierLoc());
2882 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002883 }
2884 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002885 if (!D.isInvalidType())
2886 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2887 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2888 << SourceRange(D.getIdentifierLoc());
2889 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002890 SC = FunctionDecl::None;
2891 }
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Chris Lattner65401802009-04-25 08:28:21 +00002893 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2894 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002895 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002896 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2897 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002898 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002899 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2900 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002901 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002902 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2903 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002904 }
Mike Stump1eb44332009-09-09 15:08:12 +00002905
Douglas Gregor42a552f2008-11-05 20:51:48 +00002906 // Rebuild the function type "R" without any type qualifiers (in
2907 // case any of the errors above fired) and with "void" as the
2908 // return type, since constructors don't have return types. We
2909 // *always* have to do this, because GetTypeForDeclarator will
2910 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002911 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002912 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2913 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002914 Proto->isVariadic(), 0,
2915 Proto->hasExceptionSpec(),
2916 Proto->hasAnyExceptionSpec(),
2917 Proto->getNumExceptions(),
2918 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002919 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002920}
2921
Douglas Gregor72b505b2008-12-16 21:30:33 +00002922/// CheckConstructor - Checks a fully-formed constructor for
2923/// well-formedness, issuing any diagnostics required. Returns true if
2924/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002925void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002926 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002927 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2928 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002929 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002930
2931 // C++ [class.copy]p3:
2932 // A declaration of a constructor for a class X is ill-formed if
2933 // its first parameter is of type (optionally cv-qualified) X and
2934 // either there are no other parameters or else all other
2935 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002936 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002937 ((Constructor->getNumParams() == 1) ||
2938 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002939 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2940 Constructor->getTemplateSpecializationKind()
2941 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002942 QualType ParamType = Constructor->getParamDecl(0)->getType();
2943 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2944 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002945 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2946 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor849b2432010-03-31 17:46:05 +00002947 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002948
2949 // FIXME: Rather that making the constructor invalid, we should endeavor
2950 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002951 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002952 }
2953 }
Mike Stump1eb44332009-09-09 15:08:12 +00002954
John McCall3d043362010-04-13 07:45:41 +00002955 // Notify the class that we've added a constructor. In principle we
2956 // don't need to do this for out-of-line declarations; in practice
2957 // we only instantiate the most recent declaration of a method, so
2958 // we have to call this for everything but friends.
2959 if (!Constructor->getFriendObjectKind())
2960 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002961}
2962
Anders Carlsson37909802009-11-30 21:24:50 +00002963/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2964/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002965bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002966 CXXRecordDecl *RD = Destructor->getParent();
2967
2968 if (Destructor->isVirtual()) {
2969 SourceLocation Loc;
2970
2971 if (!Destructor->isImplicit())
2972 Loc = Destructor->getLocation();
2973 else
2974 Loc = RD->getLocation();
2975
2976 // If we have a virtual destructor, look up the deallocation function
2977 FunctionDecl *OperatorDelete = 0;
2978 DeclarationName Name =
2979 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002980 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002981 return true;
2982
2983 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002984 }
Anders Carlsson37909802009-11-30 21:24:50 +00002985
2986 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002987}
2988
Mike Stump1eb44332009-09-09 15:08:12 +00002989static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002990FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2991 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2992 FTI.ArgInfo[0].Param &&
2993 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2994}
2995
Douglas Gregor42a552f2008-11-05 20:51:48 +00002996/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2997/// the well-formednes of the destructor declarator @p D with type @p
2998/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002999/// emit diagnostics and set the declarator to invalid. Even if this happens,
3000/// will be updated to reflect a well-formed type for the destructor and
3001/// returned.
3002QualType Sema::CheckDestructorDeclarator(Declarator &D,
3003 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003004 // C++ [class.dtor]p1:
3005 // [...] A typedef-name that names a class is a class-name
3006 // (7.1.3); however, a typedef-name that names a class shall not
3007 // be used as the identifier in the declarator for a destructor
3008 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003009 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00003010 if (isa<TypedefType>(DeclaratorType)) {
3011 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003012 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00003013 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003014 }
3015
3016 // C++ [class.dtor]p2:
3017 // A destructor is used to destroy objects of its class type. A
3018 // destructor takes no parameters, and no return type can be
3019 // specified for it (not even void). The address of a destructor
3020 // shall not be taken. A destructor shall not be static. A
3021 // destructor can be invoked for a const, volatile or const
3022 // volatile object. A destructor shall not be declared const,
3023 // volatile or const volatile (9.3.2).
3024 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003025 if (!D.isInvalidType())
3026 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3027 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3028 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003029 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00003030 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003031 }
Chris Lattner65401802009-04-25 08:28:21 +00003032 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003033 // Destructors don't have return types, but the parser will
3034 // happily parse something like:
3035 //
3036 // class X {
3037 // float ~X();
3038 // };
3039 //
3040 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003041 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3042 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3043 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003044 }
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Chris Lattner65401802009-04-25 08:28:21 +00003046 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3047 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003048 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003049 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3050 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003051 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003052 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3053 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003054 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003055 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3056 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003057 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003058 }
3059
3060 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003061 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003062 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3063
3064 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003065 FTI.freeArgs();
3066 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003067 }
3068
Mike Stump1eb44332009-09-09 15:08:12 +00003069 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003070 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003071 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003072 D.setInvalidType();
3073 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003074
3075 // Rebuild the function type "R" without any type qualifiers or
3076 // parameters (in case any of the errors above fired) and with
3077 // "void" as the return type, since destructors don't have return
3078 // types. We *always* have to do this, because GetTypeForDeclarator
3079 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003080 // FIXME: Exceptions!
3081 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003082 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003083}
3084
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003085/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3086/// well-formednes of the conversion function declarator @p D with
3087/// type @p R. If there are any errors in the declarator, this routine
3088/// will emit diagnostics and return true. Otherwise, it will return
3089/// false. Either way, the type @p R will be updated to reflect a
3090/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003091void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003092 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003093 // C++ [class.conv.fct]p1:
3094 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003095 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003096 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003097 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003098 if (!D.isInvalidType())
3099 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3100 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3101 << SourceRange(D.getIdentifierLoc());
3102 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003103 SC = FunctionDecl::None;
3104 }
John McCalla3f81372010-04-13 00:04:31 +00003105
3106 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3107
Chris Lattner6e475012009-04-25 08:35:12 +00003108 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003109 // Conversion functions don't have return types, but the parser will
3110 // happily parse something like:
3111 //
3112 // class X {
3113 // float operator bool();
3114 // };
3115 //
3116 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003117 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3118 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3119 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003120 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003121 }
3122
John McCalla3f81372010-04-13 00:04:31 +00003123 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3124
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003125 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003126 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003127 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3128
3129 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003130 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003131 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003132 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003133 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003134 D.setInvalidType();
3135 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003136
John McCalla3f81372010-04-13 00:04:31 +00003137 // Diagnose "&operator bool()" and other such nonsense. This
3138 // is actually a gcc extension which we don't support.
3139 if (Proto->getResultType() != ConvType) {
3140 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3141 << Proto->getResultType();
3142 D.setInvalidType();
3143 ConvType = Proto->getResultType();
3144 }
3145
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003146 // C++ [class.conv.fct]p4:
3147 // The conversion-type-id shall not represent a function type nor
3148 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003149 if (ConvType->isArrayType()) {
3150 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3151 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003152 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003153 } else if (ConvType->isFunctionType()) {
3154 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3155 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003156 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003157 }
3158
3159 // Rebuild the function type "R" without any parameters (in case any
3160 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003161 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003162 if (D.isInvalidType()) {
3163 R = Context.getFunctionType(ConvType, 0, 0, false,
3164 Proto->getTypeQuals(),
3165 Proto->hasExceptionSpec(),
3166 Proto->hasAnyExceptionSpec(),
3167 Proto->getNumExceptions(),
3168 Proto->exception_begin(),
3169 Proto->getExtInfo());
3170 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003171
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003172 // C++0x explicit conversion operators.
3173 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003174 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003175 diag::warn_explicit_conversion_functions)
3176 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003177}
3178
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003179/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3180/// the declaration of the given C++ conversion function. This routine
3181/// is responsible for recording the conversion function in the C++
3182/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003183Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003184 assert(Conversion && "Expected to receive a conversion function declaration");
3185
Douglas Gregor9d350972008-12-12 08:25:50 +00003186 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003187
3188 // Make sure we aren't redeclaring the conversion function.
3189 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003190
3191 // C++ [class.conv.fct]p1:
3192 // [...] A conversion function is never used to convert a
3193 // (possibly cv-qualified) object to the (possibly cv-qualified)
3194 // same object type (or a reference to it), to a (possibly
3195 // cv-qualified) base class of that type (or a reference to it),
3196 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003197 // FIXME: Suppress this warning if the conversion function ends up being a
3198 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003199 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003200 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003201 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003202 ConvType = ConvTypeRef->getPointeeType();
3203 if (ConvType->isRecordType()) {
3204 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3205 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003206 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003207 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003208 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003209 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003210 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003211 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003212 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003213 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003214 }
3215
Douglas Gregor48026d22010-01-11 18:40:55 +00003216 if (Conversion->getPrimaryTemplate()) {
3217 // ignore specializations
3218 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003219 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003220 = Conversion->getDescribedFunctionTemplate()) {
3221 if (ClassDecl->replaceConversion(
3222 ConversionTemplate->getPreviousDeclaration(),
3223 ConversionTemplate))
3224 return DeclPtrTy::make(ConversionTemplate);
3225 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3226 Conversion))
John McCallba135432009-11-21 08:51:07 +00003227 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00003228 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003229 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003230 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003231 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003232 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003233 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003234
Chris Lattnerb28317a2009-03-28 19:18:32 +00003235 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003236}
3237
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003238//===----------------------------------------------------------------------===//
3239// Namespace Handling
3240//===----------------------------------------------------------------------===//
3241
3242/// ActOnStartNamespaceDef - This is called at the start of a namespace
3243/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003244Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3245 SourceLocation IdentLoc,
3246 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003247 SourceLocation LBrace,
3248 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003249 NamespaceDecl *Namespc =
3250 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3251 Namespc->setLBracLoc(LBrace);
3252
3253 Scope *DeclRegionScope = NamespcScope->getParent();
3254
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003255 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3256
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003257 if (II) {
3258 // C++ [namespace.def]p2:
3259 // The identifier in an original-namespace-definition shall not have been
3260 // previously defined in the declarative region in which the
3261 // original-namespace-definition appears. The identifier in an
3262 // original-namespace-definition is the name of the namespace. Subsequently
3263 // in that declarative region, it is treated as an original-namespace-name.
3264
John McCallf36e02d2009-10-09 21:13:30 +00003265 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003266 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003267 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Douglas Gregor44b43212008-12-11 16:49:14 +00003269 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3270 // This is an extended namespace definition.
3271 // Attach this namespace decl to the chain of extended namespace
3272 // definitions.
3273 OrigNS->setNextNamespace(Namespc);
3274 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003275
Mike Stump1eb44332009-09-09 15:08:12 +00003276 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003277 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003278 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003279 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003280 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003281 } else if (PrevDecl) {
3282 // This is an invalid name redefinition.
3283 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3284 << Namespc->getDeclName();
3285 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3286 Namespc->setInvalidDecl();
3287 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003288 } else if (II->isStr("std") &&
3289 CurContext->getLookupContext()->isTranslationUnit()) {
3290 // This is the first "real" definition of the namespace "std", so update
3291 // our cache of the "std" namespace to point at this definition.
3292 if (StdNamespace) {
3293 // We had already defined a dummy namespace "std". Link this new
3294 // namespace definition to the dummy namespace "std".
3295 StdNamespace->setNextNamespace(Namespc);
3296 StdNamespace->setLocation(IdentLoc);
3297 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3298 }
3299
3300 // Make our StdNamespace cache point at the first real definition of the
3301 // "std" namespace.
3302 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003303 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003304
3305 PushOnScopeChains(Namespc, DeclRegionScope);
3306 } else {
John McCall9aeed322009-10-01 00:25:31 +00003307 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003308 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003309
3310 // Link the anonymous namespace into its parent.
3311 NamespaceDecl *PrevDecl;
3312 DeclContext *Parent = CurContext->getLookupContext();
3313 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3314 PrevDecl = TU->getAnonymousNamespace();
3315 TU->setAnonymousNamespace(Namespc);
3316 } else {
3317 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3318 PrevDecl = ND->getAnonymousNamespace();
3319 ND->setAnonymousNamespace(Namespc);
3320 }
3321
3322 // Link the anonymous namespace with its previous declaration.
3323 if (PrevDecl) {
3324 assert(PrevDecl->isAnonymousNamespace());
3325 assert(!PrevDecl->getNextNamespace());
3326 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3327 PrevDecl->setNextNamespace(Namespc);
3328 }
John McCall9aeed322009-10-01 00:25:31 +00003329
Douglas Gregora4181472010-03-24 00:46:35 +00003330 CurContext->addDecl(Namespc);
3331
John McCall9aeed322009-10-01 00:25:31 +00003332 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3333 // behaves as if it were replaced by
3334 // namespace unique { /* empty body */ }
3335 // using namespace unique;
3336 // namespace unique { namespace-body }
3337 // where all occurrences of 'unique' in a translation unit are
3338 // replaced by the same identifier and this identifier differs
3339 // from all other identifiers in the entire program.
3340
3341 // We just create the namespace with an empty name and then add an
3342 // implicit using declaration, just like the standard suggests.
3343 //
3344 // CodeGen enforces the "universally unique" aspect by giving all
3345 // declarations semantically contained within an anonymous
3346 // namespace internal linkage.
3347
John McCall5fdd7642009-12-16 02:06:49 +00003348 if (!PrevDecl) {
3349 UsingDirectiveDecl* UD
3350 = UsingDirectiveDecl::Create(Context, CurContext,
3351 /* 'using' */ LBrace,
3352 /* 'namespace' */ SourceLocation(),
3353 /* qualifier */ SourceRange(),
3354 /* NNS */ NULL,
3355 /* identifier */ SourceLocation(),
3356 Namespc,
3357 /* Ancestor */ CurContext);
3358 UD->setImplicit();
3359 CurContext->addDecl(UD);
3360 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003361 }
3362
3363 // Although we could have an invalid decl (i.e. the namespace name is a
3364 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003365 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3366 // for the namespace has the declarations that showed up in that particular
3367 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003368 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003369 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003370}
3371
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003372/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3373/// is a namespace alias, returns the namespace it points to.
3374static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3375 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3376 return AD->getNamespace();
3377 return dyn_cast_or_null<NamespaceDecl>(D);
3378}
3379
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003380/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3381/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003382void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3383 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003384 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3385 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3386 Namespc->setRBracLoc(RBrace);
3387 PopDeclContext();
3388}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003389
Chris Lattnerb28317a2009-03-28 19:18:32 +00003390Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3391 SourceLocation UsingLoc,
3392 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003393 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003394 SourceLocation IdentLoc,
3395 IdentifierInfo *NamespcName,
3396 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003397 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3398 assert(NamespcName && "Invalid NamespcName.");
3399 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003400 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003401
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003402 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003403
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003404 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003405 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3406 LookupParsedName(R, S, &SS);
3407 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003408 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003409
John McCallf36e02d2009-10-09 21:13:30 +00003410 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003411 NamedDecl *Named = R.getFoundDecl();
3412 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3413 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003414 // C++ [namespace.udir]p1:
3415 // A using-directive specifies that the names in the nominated
3416 // namespace can be used in the scope in which the
3417 // using-directive appears after the using-directive. During
3418 // unqualified name lookup (3.4.1), the names appear as if they
3419 // were declared in the nearest enclosing namespace which
3420 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003421 // namespace. [Note: in this context, "contains" means "contains
3422 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003423
3424 // Find enclosing context containing both using-directive and
3425 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003426 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003427 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3428 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3429 CommonAncestor = CommonAncestor->getParent();
3430
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003431 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003432 SS.getRange(),
3433 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003434 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003435 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003436 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003437 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003438 }
3439
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003440 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003441 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003442 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003443}
3444
3445void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3446 // If scope has associated entity, then using directive is at namespace
3447 // or translation unit scope. We add UsingDirectiveDecls, into
3448 // it's lookup structure.
3449 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003450 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003451 else
3452 // Otherwise it is block-sope. using-directives will affect lookup
3453 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003454 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003455}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003456
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003457
3458Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003459 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003460 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003461 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003462 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003463 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003464 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003465 bool IsTypeName,
3466 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003467 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Douglas Gregor12c118a2009-11-04 16:30:06 +00003469 switch (Name.getKind()) {
3470 case UnqualifiedId::IK_Identifier:
3471 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003472 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003473 case UnqualifiedId::IK_ConversionFunctionId:
3474 break;
3475
3476 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003477 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003478 // C++0x inherited constructors.
3479 if (getLangOptions().CPlusPlus0x) break;
3480
Douglas Gregor12c118a2009-11-04 16:30:06 +00003481 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3482 << SS.getRange();
3483 return DeclPtrTy();
3484
3485 case UnqualifiedId::IK_DestructorName:
3486 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3487 << SS.getRange();
3488 return DeclPtrTy();
3489
3490 case UnqualifiedId::IK_TemplateId:
3491 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3492 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3493 return DeclPtrTy();
3494 }
3495
3496 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003497 if (!TargetName)
3498 return DeclPtrTy();
3499
John McCall60fa3cf2009-12-11 02:10:03 +00003500 // Warn about using declarations.
3501 // TODO: store that the declaration was written without 'using' and
3502 // talk about access decls instead of using decls in the
3503 // diagnostics.
3504 if (!HasUsingKeyword) {
3505 UsingLoc = Name.getSourceRange().getBegin();
3506
3507 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003508 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003509 }
3510
John McCall9488ea12009-11-17 05:59:44 +00003511 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003512 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003513 TargetName, AttrList,
3514 /* IsInstantiation */ false,
3515 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003516 if (UD)
3517 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Anders Carlssonc72160b2009-08-28 05:40:36 +00003519 return DeclPtrTy::make(UD);
3520}
3521
John McCall9f54ad42009-12-10 09:41:52 +00003522/// Determines whether to create a using shadow decl for a particular
3523/// decl, given the set of decls existing prior to this using lookup.
3524bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3525 const LookupResult &Previous) {
3526 // Diagnose finding a decl which is not from a base class of the
3527 // current class. We do this now because there are cases where this
3528 // function will silently decide not to build a shadow decl, which
3529 // will pre-empt further diagnostics.
3530 //
3531 // We don't need to do this in C++0x because we do the check once on
3532 // the qualifier.
3533 //
3534 // FIXME: diagnose the following if we care enough:
3535 // struct A { int foo; };
3536 // struct B : A { using A::foo; };
3537 // template <class T> struct C : A {};
3538 // template <class T> struct D : C<T> { using B::foo; } // <---
3539 // This is invalid (during instantiation) in C++03 because B::foo
3540 // resolves to the using decl in B, which is not a base class of D<T>.
3541 // We can't diagnose it immediately because C<T> is an unknown
3542 // specialization. The UsingShadowDecl in D<T> then points directly
3543 // to A::foo, which will look well-formed when we instantiate.
3544 // The right solution is to not collapse the shadow-decl chain.
3545 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3546 DeclContext *OrigDC = Orig->getDeclContext();
3547
3548 // Handle enums and anonymous structs.
3549 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3550 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3551 while (OrigRec->isAnonymousStructOrUnion())
3552 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3553
3554 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3555 if (OrigDC == CurContext) {
3556 Diag(Using->getLocation(),
3557 diag::err_using_decl_nested_name_specifier_is_current_class)
3558 << Using->getNestedNameRange();
3559 Diag(Orig->getLocation(), diag::note_using_decl_target);
3560 return true;
3561 }
3562
3563 Diag(Using->getNestedNameRange().getBegin(),
3564 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3565 << Using->getTargetNestedNameDecl()
3566 << cast<CXXRecordDecl>(CurContext)
3567 << Using->getNestedNameRange();
3568 Diag(Orig->getLocation(), diag::note_using_decl_target);
3569 return true;
3570 }
3571 }
3572
3573 if (Previous.empty()) return false;
3574
3575 NamedDecl *Target = Orig;
3576 if (isa<UsingShadowDecl>(Target))
3577 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3578
John McCalld7533ec2009-12-11 02:33:26 +00003579 // If the target happens to be one of the previous declarations, we
3580 // don't have a conflict.
3581 //
3582 // FIXME: but we might be increasing its access, in which case we
3583 // should redeclare it.
3584 NamedDecl *NonTag = 0, *Tag = 0;
3585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3586 I != E; ++I) {
3587 NamedDecl *D = (*I)->getUnderlyingDecl();
3588 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3589 return false;
3590
3591 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3592 }
3593
John McCall9f54ad42009-12-10 09:41:52 +00003594 if (Target->isFunctionOrFunctionTemplate()) {
3595 FunctionDecl *FD;
3596 if (isa<FunctionTemplateDecl>(Target))
3597 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3598 else
3599 FD = cast<FunctionDecl>(Target);
3600
3601 NamedDecl *OldDecl = 0;
3602 switch (CheckOverload(FD, Previous, OldDecl)) {
3603 case Ovl_Overload:
3604 return false;
3605
3606 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003607 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003608 break;
3609
3610 // We found a decl with the exact signature.
3611 case Ovl_Match:
3612 if (isa<UsingShadowDecl>(OldDecl)) {
3613 // Silently ignore the possible conflict.
3614 return false;
3615 }
3616
3617 // If we're in a record, we want to hide the target, so we
3618 // return true (without a diagnostic) to tell the caller not to
3619 // build a shadow decl.
3620 if (CurContext->isRecord())
3621 return true;
3622
3623 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003624 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003625 break;
3626 }
3627
3628 Diag(Target->getLocation(), diag::note_using_decl_target);
3629 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3630 return true;
3631 }
3632
3633 // Target is not a function.
3634
John McCall9f54ad42009-12-10 09:41:52 +00003635 if (isa<TagDecl>(Target)) {
3636 // No conflict between a tag and a non-tag.
3637 if (!Tag) return false;
3638
John McCall41ce66f2009-12-10 19:51:03 +00003639 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003640 Diag(Target->getLocation(), diag::note_using_decl_target);
3641 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3642 return true;
3643 }
3644
3645 // No conflict between a tag and a non-tag.
3646 if (!NonTag) return false;
3647
John McCall41ce66f2009-12-10 19:51:03 +00003648 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003649 Diag(Target->getLocation(), diag::note_using_decl_target);
3650 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3651 return true;
3652}
3653
John McCall9488ea12009-11-17 05:59:44 +00003654/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003655UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003656 UsingDecl *UD,
3657 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003658
3659 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003660 NamedDecl *Target = Orig;
3661 if (isa<UsingShadowDecl>(Target)) {
3662 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3663 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003664 }
3665
3666 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003667 = UsingShadowDecl::Create(Context, CurContext,
3668 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003669 UD->addShadowDecl(Shadow);
3670
3671 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003672 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003673 else
John McCall604e7f12009-12-08 07:46:18 +00003674 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003675 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003676
John McCall32daa422010-03-31 01:36:47 +00003677 // Register it as a conversion if appropriate.
3678 if (Shadow->getDeclName().getNameKind()
3679 == DeclarationName::CXXConversionFunctionName)
3680 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3681
John McCall604e7f12009-12-08 07:46:18 +00003682 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3683 Shadow->setInvalidDecl();
3684
John McCall9f54ad42009-12-10 09:41:52 +00003685 return Shadow;
3686}
John McCall604e7f12009-12-08 07:46:18 +00003687
John McCall9f54ad42009-12-10 09:41:52 +00003688/// Hides a using shadow declaration. This is required by the current
3689/// using-decl implementation when a resolvable using declaration in a
3690/// class is followed by a declaration which would hide or override
3691/// one or more of the using decl's targets; for example:
3692///
3693/// struct Base { void foo(int); };
3694/// struct Derived : Base {
3695/// using Base::foo;
3696/// void foo(int);
3697/// };
3698///
3699/// The governing language is C++03 [namespace.udecl]p12:
3700///
3701/// When a using-declaration brings names from a base class into a
3702/// derived class scope, member functions in the derived class
3703/// override and/or hide member functions with the same name and
3704/// parameter types in a base class (rather than conflicting).
3705///
3706/// There are two ways to implement this:
3707/// (1) optimistically create shadow decls when they're not hidden
3708/// by existing declarations, or
3709/// (2) don't create any shadow decls (or at least don't make them
3710/// visible) until we've fully parsed/instantiated the class.
3711/// The problem with (1) is that we might have to retroactively remove
3712/// a shadow decl, which requires several O(n) operations because the
3713/// decl structures are (very reasonably) not designed for removal.
3714/// (2) avoids this but is very fiddly and phase-dependent.
3715void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003716 if (Shadow->getDeclName().getNameKind() ==
3717 DeclarationName::CXXConversionFunctionName)
3718 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3719
John McCall9f54ad42009-12-10 09:41:52 +00003720 // Remove it from the DeclContext...
3721 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003722
John McCall9f54ad42009-12-10 09:41:52 +00003723 // ...and the scope, if applicable...
3724 if (S) {
3725 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3726 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003727 }
3728
John McCall9f54ad42009-12-10 09:41:52 +00003729 // ...and the using decl.
3730 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3731
3732 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003733 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003734}
3735
John McCall7ba107a2009-11-18 02:36:19 +00003736/// Builds a using declaration.
3737///
3738/// \param IsInstantiation - Whether this call arises from an
3739/// instantiation of an unresolved using declaration. We treat
3740/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003741NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3742 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003743 CXXScopeSpec &SS,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003744 SourceLocation IdentLoc,
3745 DeclarationName Name,
3746 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003747 bool IsInstantiation,
3748 bool IsTypeName,
3749 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003750 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3751 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003752
Anders Carlsson550b14b2009-08-28 05:49:21 +00003753 // FIXME: We ignore attributes for now.
3754 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003756 if (SS.isEmpty()) {
3757 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003758 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003759 }
Mike Stump1eb44332009-09-09 15:08:12 +00003760
John McCall9f54ad42009-12-10 09:41:52 +00003761 // Do the redeclaration lookup in the current scope.
3762 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3763 ForRedeclaration);
3764 Previous.setHideTags(false);
3765 if (S) {
3766 LookupName(Previous, S);
3767
3768 // It is really dumb that we have to do this.
3769 LookupResult::Filter F = Previous.makeFilter();
3770 while (F.hasNext()) {
3771 NamedDecl *D = F.next();
3772 if (!isDeclInScope(D, CurContext, S))
3773 F.erase();
3774 }
3775 F.done();
3776 } else {
3777 assert(IsInstantiation && "no scope in non-instantiation");
3778 assert(CurContext->isRecord() && "scope not record in instantiation");
3779 LookupQualifiedName(Previous, CurContext);
3780 }
3781
Mike Stump1eb44332009-09-09 15:08:12 +00003782 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003783 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3784
John McCall9f54ad42009-12-10 09:41:52 +00003785 // Check for invalid redeclarations.
3786 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3787 return 0;
3788
3789 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003790 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3791 return 0;
3792
John McCallaf8e6ed2009-11-12 03:15:40 +00003793 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003794 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003795 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003796 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003797 // FIXME: not all declaration name kinds are legal here
3798 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3799 UsingLoc, TypenameLoc,
3800 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003801 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003802 } else {
3803 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3804 UsingLoc, SS.getRange(), NNS,
3805 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003806 }
John McCalled976492009-12-04 22:46:56 +00003807 } else {
3808 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3809 SS.getRange(), UsingLoc, NNS, Name,
3810 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003811 }
John McCalled976492009-12-04 22:46:56 +00003812 D->setAccess(AS);
3813 CurContext->addDecl(D);
3814
3815 if (!LookupContext) return D;
3816 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003817
John McCall77bb1aa2010-05-01 00:40:08 +00003818 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003819 UD->setInvalidDecl();
3820 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003821 }
3822
John McCall604e7f12009-12-08 07:46:18 +00003823 // Look up the target name.
3824
John McCalla24dc2e2009-11-17 02:14:36 +00003825 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003826
John McCall604e7f12009-12-08 07:46:18 +00003827 // Unlike most lookups, we don't always want to hide tag
3828 // declarations: tag names are visible through the using declaration
3829 // even if hidden by ordinary names, *except* in a dependent context
3830 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003831 if (!IsInstantiation)
3832 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003833
John McCalla24dc2e2009-11-17 02:14:36 +00003834 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003835
John McCallf36e02d2009-10-09 21:13:30 +00003836 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003837 Diag(IdentLoc, diag::err_no_member)
3838 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003839 UD->setInvalidDecl();
3840 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003841 }
3842
John McCalled976492009-12-04 22:46:56 +00003843 if (R.isAmbiguous()) {
3844 UD->setInvalidDecl();
3845 return UD;
3846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
John McCall7ba107a2009-11-18 02:36:19 +00003848 if (IsTypeName) {
3849 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003850 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003851 Diag(IdentLoc, diag::err_using_typename_non_type);
3852 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3853 Diag((*I)->getUnderlyingDecl()->getLocation(),
3854 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003855 UD->setInvalidDecl();
3856 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003857 }
3858 } else {
3859 // If we asked for a non-typename and we got a type, error out,
3860 // but only if this is an instantiation of an unresolved using
3861 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003862 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003863 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3864 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003865 UD->setInvalidDecl();
3866 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003867 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003868 }
3869
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003870 // C++0x N2914 [namespace.udecl]p6:
3871 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003872 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003873 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3874 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003875 UD->setInvalidDecl();
3876 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003877 }
Mike Stump1eb44332009-09-09 15:08:12 +00003878
John McCall9f54ad42009-12-10 09:41:52 +00003879 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3880 if (!CheckUsingShadowDecl(UD, *I, Previous))
3881 BuildUsingShadowDecl(S, UD, *I);
3882 }
John McCall9488ea12009-11-17 05:59:44 +00003883
3884 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003885}
3886
John McCall9f54ad42009-12-10 09:41:52 +00003887/// Checks that the given using declaration is not an invalid
3888/// redeclaration. Note that this is checking only for the using decl
3889/// itself, not for any ill-formedness among the UsingShadowDecls.
3890bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3891 bool isTypeName,
3892 const CXXScopeSpec &SS,
3893 SourceLocation NameLoc,
3894 const LookupResult &Prev) {
3895 // C++03 [namespace.udecl]p8:
3896 // C++0x [namespace.udecl]p10:
3897 // A using-declaration is a declaration and can therefore be used
3898 // repeatedly where (and only where) multiple declarations are
3899 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00003900 //
3901 // That's in non-member contexts.
3902 if (!CurContext->getLookupContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00003903 return false;
3904
3905 NestedNameSpecifier *Qual
3906 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3907
3908 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3909 NamedDecl *D = *I;
3910
3911 bool DTypename;
3912 NestedNameSpecifier *DQual;
3913 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3914 DTypename = UD->isTypeName();
3915 DQual = UD->getTargetNestedNameDecl();
3916 } else if (UnresolvedUsingValueDecl *UD
3917 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3918 DTypename = false;
3919 DQual = UD->getTargetNestedNameSpecifier();
3920 } else if (UnresolvedUsingTypenameDecl *UD
3921 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3922 DTypename = true;
3923 DQual = UD->getTargetNestedNameSpecifier();
3924 } else continue;
3925
3926 // using decls differ if one says 'typename' and the other doesn't.
3927 // FIXME: non-dependent using decls?
3928 if (isTypeName != DTypename) continue;
3929
3930 // using decls differ if they name different scopes (but note that
3931 // template instantiation can cause this check to trigger when it
3932 // didn't before instantiation).
3933 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3934 Context.getCanonicalNestedNameSpecifier(DQual))
3935 continue;
3936
3937 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003938 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003939 return true;
3940 }
3941
3942 return false;
3943}
3944
John McCall604e7f12009-12-08 07:46:18 +00003945
John McCalled976492009-12-04 22:46:56 +00003946/// Checks that the given nested-name qualifier used in a using decl
3947/// in the current context is appropriately related to the current
3948/// scope. If an error is found, diagnoses it and returns true.
3949bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3950 const CXXScopeSpec &SS,
3951 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003952 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003953
John McCall604e7f12009-12-08 07:46:18 +00003954 if (!CurContext->isRecord()) {
3955 // C++03 [namespace.udecl]p3:
3956 // C++0x [namespace.udecl]p8:
3957 // A using-declaration for a class member shall be a member-declaration.
3958
3959 // If we weren't able to compute a valid scope, it must be a
3960 // dependent class scope.
3961 if (!NamedContext || NamedContext->isRecord()) {
3962 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3963 << SS.getRange();
3964 return true;
3965 }
3966
3967 // Otherwise, everything is known to be fine.
3968 return false;
3969 }
3970
3971 // The current scope is a record.
3972
3973 // If the named context is dependent, we can't decide much.
3974 if (!NamedContext) {
3975 // FIXME: in C++0x, we can diagnose if we can prove that the
3976 // nested-name-specifier does not refer to a base class, which is
3977 // still possible in some cases.
3978
3979 // Otherwise we have to conservatively report that things might be
3980 // okay.
3981 return false;
3982 }
3983
3984 if (!NamedContext->isRecord()) {
3985 // Ideally this would point at the last name in the specifier,
3986 // but we don't have that level of source info.
3987 Diag(SS.getRange().getBegin(),
3988 diag::err_using_decl_nested_name_specifier_is_not_class)
3989 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3990 return true;
3991 }
3992
3993 if (getLangOptions().CPlusPlus0x) {
3994 // C++0x [namespace.udecl]p3:
3995 // In a using-declaration used as a member-declaration, the
3996 // nested-name-specifier shall name a base class of the class
3997 // being defined.
3998
3999 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4000 cast<CXXRecordDecl>(NamedContext))) {
4001 if (CurContext == NamedContext) {
4002 Diag(NameLoc,
4003 diag::err_using_decl_nested_name_specifier_is_current_class)
4004 << SS.getRange();
4005 return true;
4006 }
4007
4008 Diag(SS.getRange().getBegin(),
4009 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4010 << (NestedNameSpecifier*) SS.getScopeRep()
4011 << cast<CXXRecordDecl>(CurContext)
4012 << SS.getRange();
4013 return true;
4014 }
4015
4016 return false;
4017 }
4018
4019 // C++03 [namespace.udecl]p4:
4020 // A using-declaration used as a member-declaration shall refer
4021 // to a member of a base class of the class being defined [etc.].
4022
4023 // Salient point: SS doesn't have to name a base class as long as
4024 // lookup only finds members from base classes. Therefore we can
4025 // diagnose here only if we can prove that that can't happen,
4026 // i.e. if the class hierarchies provably don't intersect.
4027
4028 // TODO: it would be nice if "definitely valid" results were cached
4029 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4030 // need to be repeated.
4031
4032 struct UserData {
4033 llvm::DenseSet<const CXXRecordDecl*> Bases;
4034
4035 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4036 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4037 Data->Bases.insert(Base);
4038 return true;
4039 }
4040
4041 bool hasDependentBases(const CXXRecordDecl *Class) {
4042 return !Class->forallBases(collect, this);
4043 }
4044
4045 /// Returns true if the base is dependent or is one of the
4046 /// accumulated base classes.
4047 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4048 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4049 return !Data->Bases.count(Base);
4050 }
4051
4052 bool mightShareBases(const CXXRecordDecl *Class) {
4053 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4054 }
4055 };
4056
4057 UserData Data;
4058
4059 // Returns false if we find a dependent base.
4060 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4061 return false;
4062
4063 // Returns false if the class has a dependent base or if it or one
4064 // of its bases is present in the base set of the current context.
4065 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4066 return false;
4067
4068 Diag(SS.getRange().getBegin(),
4069 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4070 << (NestedNameSpecifier*) SS.getScopeRep()
4071 << cast<CXXRecordDecl>(CurContext)
4072 << SS.getRange();
4073
4074 return true;
John McCalled976492009-12-04 22:46:56 +00004075}
4076
Mike Stump1eb44332009-09-09 15:08:12 +00004077Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004078 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004079 SourceLocation AliasLoc,
4080 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004081 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004082 SourceLocation IdentLoc,
4083 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Anders Carlsson81c85c42009-03-28 23:53:49 +00004085 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004086 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4087 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004088
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004089 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004090 NamedDecl *PrevDecl
4091 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4092 ForRedeclaration);
4093 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4094 PrevDecl = 0;
4095
4096 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004097 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004098 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004099 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004100 // FIXME: At some point, we'll want to create the (redundant)
4101 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004102 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004103 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlsson81c85c42009-03-28 23:53:49 +00004104 return DeclPtrTy();
4105 }
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004107 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4108 diag::err_redefinition_different_kind;
4109 Diag(AliasLoc, DiagID) << Alias;
4110 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004111 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004112 }
4113
John McCalla24dc2e2009-11-17 02:14:36 +00004114 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00004115 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00004116
John McCallf36e02d2009-10-09 21:13:30 +00004117 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00004118 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004119 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00004120 }
Mike Stump1eb44332009-09-09 15:08:12 +00004121
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004122 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004123 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4124 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004125 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004126 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004127
John McCall3dbd3d52010-02-16 06:53:13 +00004128 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00004129 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00004130}
4131
Douglas Gregor39957dc2010-05-01 15:04:51 +00004132namespace {
4133 /// \brief Scoped object used to handle the state changes required in Sema
4134 /// to implicitly define the body of a C++ member function;
4135 class ImplicitlyDefinedFunctionScope {
4136 Sema &S;
4137 DeclContext *PreviousContext;
4138
4139 public:
4140 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4141 : S(S), PreviousContext(S.CurContext)
4142 {
4143 S.CurContext = Method;
4144 S.PushFunctionScope();
4145 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4146 }
4147
4148 ~ImplicitlyDefinedFunctionScope() {
4149 S.PopExpressionEvaluationContext();
4150 S.PopFunctionOrBlockScope();
4151 S.CurContext = PreviousContext;
4152 }
4153 };
4154}
4155
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004156void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4157 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004158 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4159 !Constructor->isUsed()) &&
4160 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004161
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004162 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004163 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004164
Douglas Gregor39957dc2010-05-01 15:04:51 +00004165 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004166 ErrorTrap Trap(*this);
4167 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4168 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004169 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004170 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004171 Constructor->setInvalidDecl();
4172 } else {
4173 Constructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004174 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004175 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004176}
4177
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004178void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004179 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004180 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4181 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004182 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004183 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004184
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004185 if (Destructor->isInvalidDecl())
4186 return;
4187
Douglas Gregor39957dc2010-05-01 15:04:51 +00004188 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004189
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004190 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004191 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4192 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004193
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004194 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004195 Diag(CurrentLocation, diag::note_member_synthesized_at)
4196 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4197
4198 Destructor->setInvalidDecl();
4199 return;
4200 }
4201
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004202 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004203 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004204}
4205
Douglas Gregor06a9f362010-05-01 20:49:11 +00004206/// \brief Builds a statement that copies the given entity from \p From to
4207/// \c To.
4208///
4209/// This routine is used to copy the members of a class with an
4210/// implicitly-declared copy assignment operator. When the entities being
4211/// copied are arrays, this routine builds for loops to copy them.
4212///
4213/// \param S The Sema object used for type-checking.
4214///
4215/// \param Loc The location where the implicit copy is being generated.
4216///
4217/// \param T The type of the expressions being copied. Both expressions must
4218/// have this type.
4219///
4220/// \param To The expression we are copying to.
4221///
4222/// \param From The expression we are copying from.
4223///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004224/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4225/// Otherwise, it's a non-static member subobject.
4226///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004227/// \param Depth Internal parameter recording the depth of the recursion.
4228///
4229/// \returns A statement or a loop that copies the expressions.
4230static Sema::OwningStmtResult
4231BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4232 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004233 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004234 typedef Sema::OwningStmtResult OwningStmtResult;
4235 typedef Sema::OwningExprResult OwningExprResult;
4236
4237 // C++0x [class.copy]p30:
4238 // Each subobject is assigned in the manner appropriate to its type:
4239 //
4240 // - if the subobject is of class type, the copy assignment operator
4241 // for the class is used (as if by explicit qualification; that is,
4242 // ignoring any possible virtual overriding functions in more derived
4243 // classes);
4244 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4245 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4246
4247 // Look for operator=.
4248 DeclarationName Name
4249 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4250 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4251 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4252
4253 // Filter out any result that isn't a copy-assignment operator.
4254 LookupResult::Filter F = OpLookup.makeFilter();
4255 while (F.hasNext()) {
4256 NamedDecl *D = F.next();
4257 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4258 if (Method->isCopyAssignmentOperator())
4259 continue;
4260
4261 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004262 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004263 F.done();
4264
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004265 // Suppress the protected check (C++ [class.protected]) for each of the
4266 // assignment operators we found. This strange dance is required when
4267 // we're assigning via a base classes's copy-assignment operator. To
4268 // ensure that we're getting the right base class subobject (without
4269 // ambiguities), we need to cast "this" to that subobject type; to
4270 // ensure that we don't go through the virtual call mechanism, we need
4271 // to qualify the operator= name with the base class (see below). However,
4272 // this means that if the base class has a protected copy assignment
4273 // operator, the protected member access check will fail. So, we
4274 // rewrite "protected" access to "public" access in this case, since we
4275 // know by construction that we're calling from a derived class.
4276 if (CopyingBaseSubobject) {
4277 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4278 L != LEnd; ++L) {
4279 if (L.getAccess() == AS_protected)
4280 L.setAccess(AS_public);
4281 }
4282 }
4283
Douglas Gregor06a9f362010-05-01 20:49:11 +00004284 // Create the nested-name-specifier that will be used to qualify the
4285 // reference to operator=; this is required to suppress the virtual
4286 // call mechanism.
4287 CXXScopeSpec SS;
4288 SS.setRange(Loc);
4289 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4290 T.getTypePtr()));
4291
4292 // Create the reference to operator=.
4293 OwningExprResult OpEqualRef
4294 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4295 /*FirstQualifierInScope=*/0, OpLookup,
4296 /*TemplateArgs=*/0,
4297 /*SuppressQualifierCheck=*/true);
4298 if (OpEqualRef.isInvalid())
4299 return S.StmtError();
4300
4301 // Build the call to the assignment operator.
4302 Expr *FromE = From.takeAs<Expr>();
4303 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4304 OpEqualRef.takeAs<Expr>(),
4305 Loc, &FromE, 1, 0, Loc);
4306 if (Call.isInvalid())
4307 return S.StmtError();
4308
4309 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004310 }
John McCallb0207482010-03-16 06:11:48 +00004311
Douglas Gregor06a9f362010-05-01 20:49:11 +00004312 // - if the subobject is of scalar type, the built-in assignment
4313 // operator is used.
4314 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4315 if (!ArrayTy) {
4316 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4317 BinaryOperator::Assign,
4318 To.takeAs<Expr>(),
4319 From.takeAs<Expr>());
4320 if (Assignment.isInvalid())
4321 return S.StmtError();
4322
4323 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004324 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004325
4326 // - if the subobject is an array, each element is assigned, in the
4327 // manner appropriate to the element type;
4328
4329 // Construct a loop over the array bounds, e.g.,
4330 //
4331 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4332 //
4333 // that will copy each of the array elements.
4334 QualType SizeType = S.Context.getSizeType();
4335
4336 // Create the iteration variable.
4337 IdentifierInfo *IterationVarName = 0;
4338 {
4339 llvm::SmallString<8> Str;
4340 llvm::raw_svector_ostream OS(Str);
4341 OS << "__i" << Depth;
4342 IterationVarName = &S.Context.Idents.get(OS.str());
4343 }
4344 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4345 IterationVarName, SizeType,
4346 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4347 VarDecl::None, VarDecl::None);
4348
4349 // Initialize the iteration variable to zero.
4350 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4351 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4352
4353 // Create a reference to the iteration variable; we'll use this several
4354 // times throughout.
4355 Expr *IterationVarRef
4356 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4357 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4358
4359 // Create the DeclStmt that holds the iteration variable.
4360 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4361
4362 // Create the comparison against the array bound.
4363 llvm::APInt Upper = ArrayTy->getSize();
4364 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4365 OwningExprResult Comparison
4366 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4367 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4368 BinaryOperator::NE, S.Context.BoolTy, Loc));
4369
4370 // Create the pre-increment of the iteration variable.
4371 OwningExprResult Increment
4372 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4373 UnaryOperator::PreInc,
4374 SizeType, Loc));
4375
4376 // Subscript the "from" and "to" expressions with the iteration variable.
4377 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4378 S.Owned(IterationVarRef->Retain()),
4379 Loc);
4380 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4381 S.Owned(IterationVarRef->Retain()),
4382 Loc);
4383 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4384 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4385
4386 // Build the copy for an individual element of the array.
4387 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4388 ArrayTy->getElementType(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004389 move(To), move(From),
4390 CopyingBaseSubobject, Depth+1);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004391 if (Copy.isInvalid()) {
4392 InitStmt->Destroy(S.Context);
4393 return S.StmtError();
4394 }
4395
4396 // Construct the loop that copies all elements of this array.
4397 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4398 S.MakeFullExpr(Comparison),
4399 Sema::DeclPtrTy(),
4400 S.MakeFullExpr(Increment),
4401 Loc, move(Copy));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004402}
4403
Douglas Gregor06a9f362010-05-01 20:49:11 +00004404void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4405 CXXMethodDecl *CopyAssignOperator) {
4406 assert((CopyAssignOperator->isImplicit() &&
4407 CopyAssignOperator->isOverloadedOperator() &&
4408 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4409 !CopyAssignOperator->isUsed()) &&
4410 "DefineImplicitCopyAssignment called for wrong function");
4411
4412 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4413
4414 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4415 CopyAssignOperator->setInvalidDecl();
4416 return;
4417 }
4418
4419 CopyAssignOperator->setUsed();
4420
4421 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004422 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004423
4424 // C++0x [class.copy]p30:
4425 // The implicitly-defined or explicitly-defaulted copy assignment operator
4426 // for a non-union class X performs memberwise copy assignment of its
4427 // subobjects. The direct base classes of X are assigned first, in the
4428 // order of their declaration in the base-specifier-list, and then the
4429 // immediate non-static data members of X are assigned, in the order in
4430 // which they were declared in the class definition.
4431
4432 // The statements that form the synthesized function body.
4433 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4434
4435 // The parameter for the "other" object, which we are copying from.
4436 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4437 Qualifiers OtherQuals = Other->getType().getQualifiers();
4438 QualType OtherRefType = Other->getType();
4439 if (const LValueReferenceType *OtherRef
4440 = OtherRefType->getAs<LValueReferenceType>()) {
4441 OtherRefType = OtherRef->getPointeeType();
4442 OtherQuals = OtherRefType.getQualifiers();
4443 }
4444
4445 // Our location for everything implicitly-generated.
4446 SourceLocation Loc = CopyAssignOperator->getLocation();
4447
4448 // Construct a reference to the "other" object. We'll be using this
4449 // throughout the generated ASTs.
4450 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4451 assert(OtherRef && "Reference to parameter cannot fail!");
4452
4453 // Construct the "this" pointer. We'll be using this throughout the generated
4454 // ASTs.
4455 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4456 assert(This && "Reference to this cannot fail!");
4457
4458 // Assign base classes.
4459 bool Invalid = false;
4460 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4461 E = ClassDecl->bases_end(); Base != E; ++Base) {
4462 // Form the assignment:
4463 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4464 QualType BaseType = Base->getType().getUnqualifiedType();
4465 CXXRecordDecl *BaseClassDecl = 0;
4466 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4467 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4468 else {
4469 Invalid = true;
4470 continue;
4471 }
4472
4473 // Construct the "from" expression, which is an implicit cast to the
4474 // appropriately-qualified base type.
4475 Expr *From = OtherRef->Retain();
4476 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4477 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4478 CXXBaseSpecifierArray(Base));
4479
4480 // Dereference "this".
4481 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4482 Owned(This->Retain()));
4483
4484 // Implicitly cast "this" to the appropriately-qualified base type.
4485 Expr *ToE = To.takeAs<Expr>();
4486 ImpCastExprToType(ToE,
4487 Context.getCVRQualifiedType(BaseType,
4488 CopyAssignOperator->getTypeQualifiers()),
4489 CastExpr::CK_UncheckedDerivedToBase,
4490 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4491 To = Owned(ToE);
4492
4493 // Build the copy.
4494 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004495 move(To), Owned(From),
4496 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004497 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004498 Diag(CurrentLocation, diag::note_member_synthesized_at)
4499 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4500 CopyAssignOperator->setInvalidDecl();
4501 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004502 }
4503
4504 // Success! Record the copy.
4505 Statements.push_back(Copy.takeAs<Expr>());
4506 }
4507
4508 // \brief Reference to the __builtin_memcpy function.
4509 Expr *BuiltinMemCpyRef = 0;
4510
4511 // Assign non-static members.
4512 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4513 FieldEnd = ClassDecl->field_end();
4514 Field != FieldEnd; ++Field) {
4515 // Check for members of reference type; we can't copy those.
4516 if (Field->getType()->isReferenceType()) {
4517 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4518 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4519 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004520 Diag(CurrentLocation, diag::note_member_synthesized_at)
4521 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004522 Invalid = true;
4523 continue;
4524 }
4525
4526 // Check for members of const-qualified, non-class type.
4527 QualType BaseType = Context.getBaseElementType(Field->getType());
4528 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4529 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4530 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4531 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004532 Diag(CurrentLocation, diag::note_member_synthesized_at)
4533 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004534 Invalid = true;
4535 continue;
4536 }
4537
4538 QualType FieldType = Field->getType().getNonReferenceType();
4539
4540 // Build references to the field in the object we're copying from and to.
4541 CXXScopeSpec SS; // Intentionally empty
4542 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4543 LookupMemberName);
4544 MemberLookup.addDecl(*Field);
4545 MemberLookup.resolveKind();
4546 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4547 OtherRefType,
4548 Loc, /*IsArrow=*/false,
4549 SS, 0, MemberLookup, 0);
4550 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4551 This->getType(),
4552 Loc, /*IsArrow=*/true,
4553 SS, 0, MemberLookup, 0);
4554 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4555 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4556
4557 // If the field should be copied with __builtin_memcpy rather than via
4558 // explicit assignments, do so. This optimization only applies for arrays
4559 // of scalars and arrays of class type with trivial copy-assignment
4560 // operators.
4561 if (FieldType->isArrayType() &&
4562 (!BaseType->isRecordType() ||
4563 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4564 ->hasTrivialCopyAssignment())) {
4565 // Compute the size of the memory buffer to be copied.
4566 QualType SizeType = Context.getSizeType();
4567 llvm::APInt Size(Context.getTypeSize(SizeType),
4568 Context.getTypeSizeInChars(BaseType).getQuantity());
4569 for (const ConstantArrayType *Array
4570 = Context.getAsConstantArrayType(FieldType);
4571 Array;
4572 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4573 llvm::APInt ArraySize = Array->getSize();
4574 ArraySize.zextOrTrunc(Size.getBitWidth());
4575 Size *= ArraySize;
4576 }
4577
4578 // Take the address of the field references for "from" and "to".
4579 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4580 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4581
4582 // Create a reference to the __builtin_memcpy builtin function.
4583 if (!BuiltinMemCpyRef) {
4584 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4585 LookupOrdinaryName);
4586 LookupName(R, TUScope, true);
4587
4588 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4589 if (!BuiltinMemCpy) {
4590 // Something went horribly wrong earlier, and we will have complained
4591 // about it.
4592 Invalid = true;
4593 continue;
4594 }
4595
4596 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4597 BuiltinMemCpy->getType(),
4598 Loc, 0).takeAs<Expr>();
4599 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4600 }
4601
4602 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4603 CallArgs.push_back(To.takeAs<Expr>());
4604 CallArgs.push_back(From.takeAs<Expr>());
4605 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4606 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4607 Commas.push_back(Loc);
4608 Commas.push_back(Loc);
4609 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4610 Owned(BuiltinMemCpyRef->Retain()),
4611 Loc, move_arg(CallArgs),
4612 Commas.data(), Loc);
4613 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4614 Statements.push_back(Call.takeAs<Expr>());
4615 continue;
4616 }
4617
4618 // Build the copy of this field.
4619 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004620 move(To), move(From),
4621 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004622 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004623 Diag(CurrentLocation, diag::note_member_synthesized_at)
4624 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4625 CopyAssignOperator->setInvalidDecl();
4626 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004627 }
4628
4629 // Success! Record the copy.
4630 Statements.push_back(Copy.takeAs<Stmt>());
4631 }
4632
4633 if (!Invalid) {
4634 // Add a "return *this;"
4635 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4636 Owned(This->Retain()));
4637
4638 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4639 if (Return.isInvalid())
4640 Invalid = true;
4641 else {
4642 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004643
4644 if (Trap.hasErrorOccurred()) {
4645 Diag(CurrentLocation, diag::note_member_synthesized_at)
4646 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4647 Invalid = true;
4648 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004649 }
4650 }
4651
4652 if (Invalid) {
4653 CopyAssignOperator->setInvalidDecl();
4654 return;
4655 }
4656
4657 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4658 /*isStmtExpr=*/false);
4659 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4660 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004661}
4662
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004663void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4664 CXXConstructorDecl *CopyConstructor,
4665 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00004666 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00004667 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004668 !CopyConstructor->isUsed()) &&
4669 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004670
Anders Carlsson63010a72010-04-23 16:24:12 +00004671 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004672 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004673
Douglas Gregor39957dc2010-05-01 15:04:51 +00004674 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004675 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004676
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004677 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
4678 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00004679 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00004680 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00004681 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00004682 } else {
4683 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
4684 CopyConstructor->getLocation(),
4685 MultiStmtArg(*this, 0, 0),
4686 /*isStmtExpr=*/false)
4687 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00004688 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00004689
4690 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004691}
4692
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004693Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004694Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00004695 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00004696 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004697 bool RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004698 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004699 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004700
Douglas Gregor2f599792010-04-02 18:24:57 +00004701 // C++0x [class.copy]p34:
4702 // When certain criteria are met, an implementation is allowed to
4703 // omit the copy/move construction of a class object, even if the
4704 // copy/move constructor and/or destructor for the object have
4705 // side effects. [...]
4706 // - when a temporary class object that has not been bound to a
4707 // reference (12.2) would be copied/moved to a class object
4708 // with the same cv-unqualified type, the copy/move operation
4709 // can be omitted by constructing the temporary object
4710 // directly into the target of the omitted copy/move
4711 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4712 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4713 Elidable = SubExpr->isTemporaryObject() &&
4714 Context.hasSameUnqualifiedType(SubExpr->getType(),
4715 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004716 }
Mike Stump1eb44332009-09-09 15:08:12 +00004717
4718 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004719 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004720 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004721}
4722
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004723/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4724/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004725Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004726Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4727 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004728 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004729 bool RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004730 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004731 unsigned NumExprs = ExprArgs.size();
4732 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Douglas Gregor7edfb692009-11-23 12:27:39 +00004734 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004735 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004736 Constructor, Elidable, Exprs, NumExprs,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004737 RequiresZeroInit, ConstructKind));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004738}
4739
Mike Stump1eb44332009-09-09 15:08:12 +00004740bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004741 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004742 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004743 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004744 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004745 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004746 if (TempResult.isInvalid())
4747 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004749 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004750 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004751 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004752 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Anders Carlssonfe2de492009-08-25 05:18:00 +00004754 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004755}
4756
John McCall68c6c9a2010-02-02 09:10:11 +00004757void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4758 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004759 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4760 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004761 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4762 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00004763 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004764 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00004765 << VD->getDeclName()
4766 << VD->getType());
John McCall4f9506a2010-02-02 08:45:54 +00004767 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004768}
4769
Mike Stump1eb44332009-09-09 15:08:12 +00004770/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004771/// ActOnDeclarator, when a C++ direct initializer is present.
4772/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004773void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4774 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004775 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004776 SourceLocation *CommaLocs,
4777 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004778 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004779 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004780
4781 // If there is no declaration, there was an error parsing it. Just ignore
4782 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004783 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004784 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004785
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004786 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4787 if (!VDecl) {
4788 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4789 RealDecl->setInvalidDecl();
4790 return;
4791 }
4792
Douglas Gregor83ddad32009-08-26 21:14:46 +00004793 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004794 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004795 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4796 //
4797 // Clients that want to distinguish between the two forms, can check for
4798 // direct initializer using VarDecl::hasCXXDirectInitializer().
4799 // A major benefit is that clients that don't particularly care about which
4800 // exactly form was it (like the CodeGen) can handle both cases without
4801 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004802
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004803 // C++ 8.5p11:
4804 // The form of initialization (using parentheses or '=') is generally
4805 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004806 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004807 QualType DeclInitType = VDecl->getType();
4808 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004809 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004810
Douglas Gregor4dffad62010-02-11 22:55:30 +00004811 if (!VDecl->getType()->isDependentType() &&
4812 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004813 diag::err_typecheck_decl_incomplete_type)) {
4814 VDecl->setInvalidDecl();
4815 return;
4816 }
4817
Douglas Gregor90f93822009-12-22 22:17:25 +00004818 // The variable can not have an abstract class type.
4819 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4820 diag::err_abstract_type_in_decl,
4821 AbstractVariableType))
4822 VDecl->setInvalidDecl();
4823
Sebastian Redl31310a22010-02-01 20:16:42 +00004824 const VarDecl *Def;
4825 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004826 Diag(VDecl->getLocation(), diag::err_redefinition)
4827 << VDecl->getDeclName();
4828 Diag(Def->getLocation(), diag::note_previous_definition);
4829 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004830 return;
4831 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004832
4833 // If either the declaration has a dependent type or if any of the
4834 // expressions is type-dependent, we represent the initialization
4835 // via a ParenListExpr for later use during template instantiation.
4836 if (VDecl->getType()->isDependentType() ||
4837 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4838 // Let clients know that initialization was done with a direct initializer.
4839 VDecl->setCXXDirectInitializer(true);
4840
4841 // Store the initialization expressions as a ParenListExpr.
4842 unsigned NumExprs = Exprs.size();
4843 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4844 (Expr **)Exprs.release(),
4845 NumExprs, RParenLoc));
4846 return;
4847 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004848
4849 // Capture the variable that is being initialized and the style of
4850 // initialization.
4851 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4852
4853 // FIXME: Poor source location information.
4854 InitializationKind Kind
4855 = InitializationKind::CreateDirect(VDecl->getLocation(),
4856 LParenLoc, RParenLoc);
4857
4858 InitializationSequence InitSeq(*this, Entity, Kind,
4859 (Expr**)Exprs.get(), Exprs.size());
4860 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4861 if (Result.isInvalid()) {
4862 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004863 return;
4864 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004865
4866 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004867 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004868 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004869
John McCall68c6c9a2010-02-02 09:10:11 +00004870 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4871 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004872}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004873
Douglas Gregor39da0b82009-09-09 23:08:42 +00004874/// \brief Given a constructor and the set of arguments provided for the
4875/// constructor, convert the arguments and add any required default arguments
4876/// to form a proper call to this constructor.
4877///
4878/// \returns true if an error occurred, false otherwise.
4879bool
4880Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4881 MultiExprArg ArgsPtr,
4882 SourceLocation Loc,
4883 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4884 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4885 unsigned NumArgs = ArgsPtr.size();
4886 Expr **Args = (Expr **)ArgsPtr.get();
4887
4888 const FunctionProtoType *Proto
4889 = Constructor->getType()->getAs<FunctionProtoType>();
4890 assert(Proto && "Constructor without a prototype?");
4891 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004892
4893 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004894 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004895 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004896 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004897 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004898
4899 VariadicCallType CallType =
4900 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4901 llvm::SmallVector<Expr *, 8> AllArgs;
4902 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4903 Proto, 0, Args, NumArgs, AllArgs,
4904 CallType);
4905 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4906 ConvertedArgs.push_back(AllArgs[i]);
4907 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004908}
4909
Anders Carlsson20d45d22009-12-12 00:32:00 +00004910static inline bool
4911CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4912 const FunctionDecl *FnDecl) {
4913 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4914 if (isa<NamespaceDecl>(DC)) {
4915 return SemaRef.Diag(FnDecl->getLocation(),
4916 diag::err_operator_new_delete_declared_in_namespace)
4917 << FnDecl->getDeclName();
4918 }
4919
4920 if (isa<TranslationUnitDecl>(DC) &&
4921 FnDecl->getStorageClass() == FunctionDecl::Static) {
4922 return SemaRef.Diag(FnDecl->getLocation(),
4923 diag::err_operator_new_delete_declared_static)
4924 << FnDecl->getDeclName();
4925 }
4926
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004927 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004928}
4929
Anders Carlsson156c78e2009-12-13 17:53:43 +00004930static inline bool
4931CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4932 CanQualType ExpectedResultType,
4933 CanQualType ExpectedFirstParamType,
4934 unsigned DependentParamTypeDiag,
4935 unsigned InvalidParamTypeDiag) {
4936 QualType ResultType =
4937 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4938
4939 // Check that the result type is not dependent.
4940 if (ResultType->isDependentType())
4941 return SemaRef.Diag(FnDecl->getLocation(),
4942 diag::err_operator_new_delete_dependent_result_type)
4943 << FnDecl->getDeclName() << ExpectedResultType;
4944
4945 // Check that the result type is what we expect.
4946 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4947 return SemaRef.Diag(FnDecl->getLocation(),
4948 diag::err_operator_new_delete_invalid_result_type)
4949 << FnDecl->getDeclName() << ExpectedResultType;
4950
4951 // A function template must have at least 2 parameters.
4952 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4953 return SemaRef.Diag(FnDecl->getLocation(),
4954 diag::err_operator_new_delete_template_too_few_parameters)
4955 << FnDecl->getDeclName();
4956
4957 // The function decl must have at least 1 parameter.
4958 if (FnDecl->getNumParams() == 0)
4959 return SemaRef.Diag(FnDecl->getLocation(),
4960 diag::err_operator_new_delete_too_few_parameters)
4961 << FnDecl->getDeclName();
4962
4963 // Check the the first parameter type is not dependent.
4964 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4965 if (FirstParamType->isDependentType())
4966 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4967 << FnDecl->getDeclName() << ExpectedFirstParamType;
4968
4969 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004970 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004971 ExpectedFirstParamType)
4972 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4973 << FnDecl->getDeclName() << ExpectedFirstParamType;
4974
4975 return false;
4976}
4977
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004978static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004979CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004980 // C++ [basic.stc.dynamic.allocation]p1:
4981 // A program is ill-formed if an allocation function is declared in a
4982 // namespace scope other than global scope or declared static in global
4983 // scope.
4984 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4985 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004986
4987 CanQualType SizeTy =
4988 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4989
4990 // C++ [basic.stc.dynamic.allocation]p1:
4991 // The return type shall be void*. The first parameter shall have type
4992 // std::size_t.
4993 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4994 SizeTy,
4995 diag::err_operator_new_dependent_param_type,
4996 diag::err_operator_new_param_type))
4997 return true;
4998
4999 // C++ [basic.stc.dynamic.allocation]p1:
5000 // The first parameter shall not have an associated default argument.
5001 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005002 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005003 diag::err_operator_new_default_arg)
5004 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5005
5006 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005007}
5008
5009static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005010CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5011 // C++ [basic.stc.dynamic.deallocation]p1:
5012 // A program is ill-formed if deallocation functions are declared in a
5013 // namespace scope other than global scope or declared static in global
5014 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005015 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5016 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005017
5018 // C++ [basic.stc.dynamic.deallocation]p2:
5019 // Each deallocation function shall return void and its first parameter
5020 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005021 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5022 SemaRef.Context.VoidPtrTy,
5023 diag::err_operator_delete_dependent_param_type,
5024 diag::err_operator_delete_param_type))
5025 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005026
Anders Carlsson46991d62009-12-12 00:16:02 +00005027 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5028 if (FirstParamType->isDependentType())
5029 return SemaRef.Diag(FnDecl->getLocation(),
5030 diag::err_operator_delete_dependent_param_type)
5031 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5032
5033 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
5034 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005035 return SemaRef.Diag(FnDecl->getLocation(),
5036 diag::err_operator_delete_param_type)
5037 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005038
5039 return false;
5040}
5041
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005042/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5043/// of this overloaded operator is well-formed. If so, returns false;
5044/// otherwise, emits appropriate diagnostics and returns true.
5045bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005046 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005047 "Expected an overloaded operator declaration");
5048
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005049 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5050
Mike Stump1eb44332009-09-09 15:08:12 +00005051 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005052 // The allocation and deallocation functions, operator new,
5053 // operator new[], operator delete and operator delete[], are
5054 // described completely in 3.7.3. The attributes and restrictions
5055 // found in the rest of this subclause do not apply to them unless
5056 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005057 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005058 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005059
Anders Carlssona3ccda52009-12-12 00:26:23 +00005060 if (Op == OO_New || Op == OO_Array_New)
5061 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005062
5063 // C++ [over.oper]p6:
5064 // An operator function shall either be a non-static member
5065 // function or be a non-member function and have at least one
5066 // parameter whose type is a class, a reference to a class, an
5067 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005068 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5069 if (MethodDecl->isStatic())
5070 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005071 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005072 } else {
5073 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005074 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5075 ParamEnd = FnDecl->param_end();
5076 Param != ParamEnd; ++Param) {
5077 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005078 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5079 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005080 ClassOrEnumParam = true;
5081 break;
5082 }
5083 }
5084
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005085 if (!ClassOrEnumParam)
5086 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005087 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005088 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005089 }
5090
5091 // C++ [over.oper]p8:
5092 // An operator function cannot have default arguments (8.3.6),
5093 // except where explicitly stated below.
5094 //
Mike Stump1eb44332009-09-09 15:08:12 +00005095 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005096 // (C++ [over.call]p1).
5097 if (Op != OO_Call) {
5098 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5099 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005100 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005101 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005102 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005103 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005104 }
5105 }
5106
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005107 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5108 { false, false, false }
5109#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5110 , { Unary, Binary, MemberOnly }
5111#include "clang/Basic/OperatorKinds.def"
5112 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005113
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005114 bool CanBeUnaryOperator = OperatorUses[Op][0];
5115 bool CanBeBinaryOperator = OperatorUses[Op][1];
5116 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005117
5118 // C++ [over.oper]p8:
5119 // [...] Operator functions cannot have more or fewer parameters
5120 // than the number required for the corresponding operator, as
5121 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005122 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005123 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005124 if (Op != OO_Call &&
5125 ((NumParams == 1 && !CanBeUnaryOperator) ||
5126 (NumParams == 2 && !CanBeBinaryOperator) ||
5127 (NumParams < 1) || (NumParams > 2))) {
5128 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005129 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005130 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005131 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005132 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005133 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005134 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005135 assert(CanBeBinaryOperator &&
5136 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005137 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005138 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005139
Chris Lattner416e46f2008-11-21 07:57:12 +00005140 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005141 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005142 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005143
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005144 // Overloaded operators other than operator() cannot be variadic.
5145 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005146 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005147 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005148 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005149 }
5150
5151 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005152 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5153 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005154 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005155 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005156 }
5157
5158 // C++ [over.inc]p1:
5159 // The user-defined function called operator++ implements the
5160 // prefix and postfix ++ operator. If this function is a member
5161 // function with no parameters, or a non-member function with one
5162 // parameter of class or enumeration type, it defines the prefix
5163 // increment operator ++ for objects of that type. If the function
5164 // is a member function with one parameter (which shall be of type
5165 // int) or a non-member function with two parameters (the second
5166 // of which shall be of type int), it defines the postfix
5167 // increment operator ++ for objects of that type.
5168 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5169 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5170 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005171 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005172 ParamIsInt = BT->getKind() == BuiltinType::Int;
5173
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005174 if (!ParamIsInt)
5175 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005176 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005177 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005178 }
5179
Sebastian Redl64b45f72009-01-05 20:52:13 +00005180 // Notify the class if it got an assignment operator.
5181 if (Op == OO_Equal) {
5182 // Would have returned earlier otherwise.
5183 assert(isa<CXXMethodDecl>(FnDecl) &&
5184 "Overloaded = not member, but not filtered.");
5185 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5186 Method->getParent()->addedAssignmentOperator(Context, Method);
5187 }
5188
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005189 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005190}
Chris Lattner5a003a42008-12-17 07:09:26 +00005191
Sean Hunta6c058d2010-01-13 09:01:02 +00005192/// CheckLiteralOperatorDeclaration - Check whether the declaration
5193/// of this literal operator function is well-formed. If so, returns
5194/// false; otherwise, emits appropriate diagnostics and returns true.
5195bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5196 DeclContext *DC = FnDecl->getDeclContext();
5197 Decl::Kind Kind = DC->getDeclKind();
5198 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5199 Kind != Decl::LinkageSpec) {
5200 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5201 << FnDecl->getDeclName();
5202 return true;
5203 }
5204
5205 bool Valid = false;
5206
Sean Hunt216c2782010-04-07 23:11:06 +00005207 // template <char...> type operator "" name() is the only valid template
5208 // signature, and the only valid signature with no parameters.
5209 if (FnDecl->param_size() == 0) {
5210 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5211 // Must have only one template parameter
5212 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5213 if (Params->size() == 1) {
5214 NonTypeTemplateParmDecl *PmDecl =
5215 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005216
Sean Hunt216c2782010-04-07 23:11:06 +00005217 // The template parameter must be a char parameter pack.
5218 // FIXME: This test will always fail because non-type parameter packs
5219 // have not been implemented.
5220 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5221 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5222 Valid = true;
5223 }
5224 }
5225 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005226 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005227 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5228
Sean Hunta6c058d2010-01-13 09:01:02 +00005229 QualType T = (*Param)->getType();
5230
Sean Hunt30019c02010-04-07 22:57:35 +00005231 // unsigned long long int, long double, and any character type are allowed
5232 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005233 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5234 Context.hasSameType(T, Context.LongDoubleTy) ||
5235 Context.hasSameType(T, Context.CharTy) ||
5236 Context.hasSameType(T, Context.WCharTy) ||
5237 Context.hasSameType(T, Context.Char16Ty) ||
5238 Context.hasSameType(T, Context.Char32Ty)) {
5239 if (++Param == FnDecl->param_end())
5240 Valid = true;
5241 goto FinishedParams;
5242 }
5243
Sean Hunt30019c02010-04-07 22:57:35 +00005244 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005245 const PointerType *PT = T->getAs<PointerType>();
5246 if (!PT)
5247 goto FinishedParams;
5248 T = PT->getPointeeType();
5249 if (!T.isConstQualified())
5250 goto FinishedParams;
5251 T = T.getUnqualifiedType();
5252
5253 // Move on to the second parameter;
5254 ++Param;
5255
5256 // If there is no second parameter, the first must be a const char *
5257 if (Param == FnDecl->param_end()) {
5258 if (Context.hasSameType(T, Context.CharTy))
5259 Valid = true;
5260 goto FinishedParams;
5261 }
5262
5263 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5264 // are allowed as the first parameter to a two-parameter function
5265 if (!(Context.hasSameType(T, Context.CharTy) ||
5266 Context.hasSameType(T, Context.WCharTy) ||
5267 Context.hasSameType(T, Context.Char16Ty) ||
5268 Context.hasSameType(T, Context.Char32Ty)))
5269 goto FinishedParams;
5270
5271 // The second and final parameter must be an std::size_t
5272 T = (*Param)->getType().getUnqualifiedType();
5273 if (Context.hasSameType(T, Context.getSizeType()) &&
5274 ++Param == FnDecl->param_end())
5275 Valid = true;
5276 }
5277
5278 // FIXME: This diagnostic is absolutely terrible.
5279FinishedParams:
5280 if (!Valid) {
5281 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5282 << FnDecl->getDeclName();
5283 return true;
5284 }
5285
5286 return false;
5287}
5288
Douglas Gregor074149e2009-01-05 19:45:36 +00005289/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5290/// linkage specification, including the language and (if present)
5291/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5292/// the location of the language string literal, which is provided
5293/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5294/// the '{' brace. Otherwise, this linkage specification does not
5295/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005296Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5297 SourceLocation ExternLoc,
5298 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00005299 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005300 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005301 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005302 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005303 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005304 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005305 Language = LinkageSpecDecl::lang_cxx;
5306 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005307 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005308 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005309 }
Mike Stump1eb44332009-09-09 15:08:12 +00005310
Chris Lattnercc98eac2008-12-17 07:13:27 +00005311 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005312
Douglas Gregor074149e2009-01-05 19:45:36 +00005313 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005314 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005315 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005316 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005317 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005318 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005319}
5320
Douglas Gregor074149e2009-01-05 19:45:36 +00005321/// ActOnFinishLinkageSpecification - Completely the definition of
5322/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5323/// valid, it's the position of the closing '}' brace in a linkage
5324/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005325Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5326 DeclPtrTy LinkageSpec,
5327 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005328 if (LinkageSpec)
5329 PopDeclContext();
5330 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005331}
5332
Douglas Gregord308e622009-05-18 20:51:54 +00005333/// \brief Perform semantic analysis for the variable declaration that
5334/// occurs within a C++ catch clause, returning the newly-created
5335/// variable.
5336VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005337 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005338 IdentifierInfo *Name,
5339 SourceLocation Loc,
5340 SourceRange Range) {
5341 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005342
5343 // Arrays and functions decay.
5344 if (ExDeclType->isArrayType())
5345 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5346 else if (ExDeclType->isFunctionType())
5347 ExDeclType = Context.getPointerType(ExDeclType);
5348
5349 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5350 // The exception-declaration shall not denote a pointer or reference to an
5351 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005352 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005353 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005354 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005355 Invalid = true;
5356 }
Douglas Gregord308e622009-05-18 20:51:54 +00005357
Douglas Gregora2762912010-03-08 01:47:36 +00005358 // GCC allows catching pointers and references to incomplete types
5359 // as an extension; so do we, but we warn by default.
5360
Sebastian Redl4b07b292008-12-22 19:15:10 +00005361 QualType BaseType = ExDeclType;
5362 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005363 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00005364 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00005365 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005366 BaseType = Ptr->getPointeeType();
5367 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00005368 DK = diag::ext_catch_incomplete_ptr;
5369 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005370 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005371 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005372 BaseType = Ref->getPointeeType();
5373 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00005374 DK = diag::ext_catch_incomplete_ref;
5375 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005376 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005377 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00005378 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5379 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00005380 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005381
Mike Stump1eb44332009-09-09 15:08:12 +00005382 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005383 RequireNonAbstractType(Loc, ExDeclType,
5384 diag::err_abstract_type_in_decl,
5385 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005386 Invalid = true;
5387
Mike Stump1eb44332009-09-09 15:08:12 +00005388 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005389 Name, ExDeclType, TInfo, VarDecl::None,
5390 VarDecl::None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00005391 ExDecl->setExceptionVariable(true);
5392
Douglas Gregor6d182892010-03-05 23:38:39 +00005393 if (!Invalid) {
5394 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5395 // C++ [except.handle]p16:
5396 // The object declared in an exception-declaration or, if the
5397 // exception-declaration does not specify a name, a temporary (12.2) is
5398 // copy-initialized (8.5) from the exception object. [...]
5399 // The object is destroyed when the handler exits, after the destruction
5400 // of any automatic objects initialized within the handler.
5401 //
5402 // We just pretend to initialize the object with itself, then make sure
5403 // it can be destroyed later.
5404 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5405 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5406 Loc, ExDeclType, 0);
5407 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5408 SourceLocation());
5409 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5410 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5411 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5412 if (Result.isInvalid())
5413 Invalid = true;
5414 else
5415 FinalizeVarWithDestructor(ExDecl, RecordTy);
5416 }
5417 }
5418
Douglas Gregord308e622009-05-18 20:51:54 +00005419 if (Invalid)
5420 ExDecl->setInvalidDecl();
5421
5422 return ExDecl;
5423}
5424
5425/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5426/// handler.
5427Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005428 TypeSourceInfo *TInfo = 0;
5429 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005430
5431 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005432 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00005433 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00005434 LookupOrdinaryName,
5435 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005436 // The scope should be freshly made just for us. There is just no way
5437 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005438 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005439 if (PrevDecl->isTemplateParameter()) {
5440 // Maybe we will complain about the shadowed template parameter.
5441 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005442 }
5443 }
5444
Chris Lattnereaaebc72009-04-25 08:06:05 +00005445 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005446 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5447 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005448 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005449 }
5450
John McCalla93c9342009-12-07 02:54:59 +00005451 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005452 D.getIdentifier(),
5453 D.getIdentifierLoc(),
5454 D.getDeclSpec().getSourceRange());
5455
Chris Lattnereaaebc72009-04-25 08:06:05 +00005456 if (Invalid)
5457 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005458
Sebastian Redl4b07b292008-12-22 19:15:10 +00005459 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005460 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005461 PushOnScopeChains(ExDecl, S);
5462 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005463 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005464
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005465 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005466 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005467}
Anders Carlssonfb311762009-03-14 00:25:26 +00005468
Mike Stump1eb44332009-09-09 15:08:12 +00005469Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005470 ExprArg assertexpr,
5471 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005472 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005473 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005474 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5475
Anders Carlssonc3082412009-03-14 00:33:21 +00005476 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5477 llvm::APSInt Value(32);
5478 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5479 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5480 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005481 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005482 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005483
Anders Carlssonc3082412009-03-14 00:33:21 +00005484 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005485 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005486 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005487 }
5488 }
Mike Stump1eb44332009-09-09 15:08:12 +00005489
Anders Carlsson77d81422009-03-15 17:35:16 +00005490 assertexpr.release();
5491 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005492 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005493 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005495 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005496 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005497}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005498
Douglas Gregor1d869352010-04-07 16:53:43 +00005499/// \brief Perform semantic analysis of the given friend type declaration.
5500///
5501/// \returns A friend declaration that.
5502FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5503 TypeSourceInfo *TSInfo) {
5504 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5505
5506 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005507 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00005508
Douglas Gregor06245bf2010-04-07 17:57:12 +00005509 if (!getLangOptions().CPlusPlus0x) {
5510 // C++03 [class.friend]p2:
5511 // An elaborated-type-specifier shall be used in a friend declaration
5512 // for a class.*
5513 //
5514 // * The class-key of the elaborated-type-specifier is required.
5515 if (!ActiveTemplateInstantiations.empty()) {
5516 // Do not complain about the form of friend template types during
5517 // template instantiation; we will already have complained when the
5518 // template was declared.
5519 } else if (!T->isElaboratedTypeSpecifier()) {
5520 // If we evaluated the type to a record type, suggest putting
5521 // a tag in front.
5522 if (const RecordType *RT = T->getAs<RecordType>()) {
5523 RecordDecl *RD = RT->getDecl();
5524
5525 std::string InsertionText = std::string(" ") + RD->getKindName();
5526
5527 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5528 << (unsigned) RD->getTagKind()
5529 << T
5530 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5531 InsertionText);
5532 } else {
5533 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5534 << T
5535 << SourceRange(FriendLoc, TypeRange.getEnd());
5536 }
5537 } else if (T->getAs<EnumType>()) {
5538 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00005539 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00005540 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00005541 }
5542 }
5543
Douglas Gregor06245bf2010-04-07 17:57:12 +00005544 // C++0x [class.friend]p3:
5545 // If the type specifier in a friend declaration designates a (possibly
5546 // cv-qualified) class type, that class is declared as a friend; otherwise,
5547 // the friend declaration is ignored.
5548
5549 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5550 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00005551
5552 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5553}
5554
John McCalldd4a3b02009-09-16 22:47:08 +00005555/// Handle a friend type declaration. This works in tandem with
5556/// ActOnTag.
5557///
5558/// Notes on friend class templates:
5559///
5560/// We generally treat friend class declarations as if they were
5561/// declaring a class. So, for example, the elaborated type specifier
5562/// in a friend declaration is required to obey the restrictions of a
5563/// class-head (i.e. no typedefs in the scope chain), template
5564/// parameters are required to match up with simple template-ids, &c.
5565/// However, unlike when declaring a template specialization, it's
5566/// okay to refer to a template specialization without an empty
5567/// template parameter declaration, e.g.
5568/// friend class A<T>::B<unsigned>;
5569/// We permit this as a special case; if there are any template
5570/// parameters present at all, require proper matching, i.e.
5571/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005572Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005573 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005574 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005575
5576 assert(DS.isFriendSpecified());
5577 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5578
John McCalldd4a3b02009-09-16 22:47:08 +00005579 // Try to convert the decl specifier to a type. This works for
5580 // friend templates because ActOnTag never produces a ClassTemplateDecl
5581 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005582 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall32f2fb52010-03-25 18:04:51 +00005583 TypeSourceInfo *TSI;
5584 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005585 if (TheDeclarator.isInvalidType())
5586 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005587
Douglas Gregor1d869352010-04-07 16:53:43 +00005588 if (!TSI)
5589 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5590
John McCalldd4a3b02009-09-16 22:47:08 +00005591 // This is definitely an error in C++98. It's probably meant to
5592 // be forbidden in C++0x, too, but the specification is just
5593 // poorly written.
5594 //
5595 // The problem is with declarations like the following:
5596 // template <T> friend A<T>::foo;
5597 // where deciding whether a class C is a friend or not now hinges
5598 // on whether there exists an instantiation of A that causes
5599 // 'foo' to equal C. There are restrictions on class-heads
5600 // (which we declare (by fiat) elaborated friend declarations to
5601 // be) that makes this tractable.
5602 //
5603 // FIXME: handle "template <> friend class A<T>;", which
5604 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00005605 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00005606 Diag(Loc, diag::err_tagless_friend_type_template)
5607 << DS.getSourceRange();
5608 return DeclPtrTy();
5609 }
Douglas Gregor1d869352010-04-07 16:53:43 +00005610
John McCall02cace72009-08-28 07:59:38 +00005611 // C++98 [class.friend]p1: A friend of a class is a function
5612 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005613 // This is fixed in DR77, which just barely didn't make the C++03
5614 // deadline. It's also a very silly restriction that seriously
5615 // affects inner classes and which nobody else seems to implement;
5616 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00005617 //
5618 // But note that we could warn about it: it's always useless to
5619 // friend one of your own members (it's not, however, worthless to
5620 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00005621
John McCalldd4a3b02009-09-16 22:47:08 +00005622 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00005623 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00005624 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00005625 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00005626 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00005627 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00005628 DS.getFriendSpecLoc());
5629 else
Douglas Gregor1d869352010-04-07 16:53:43 +00005630 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5631
5632 if (!D)
5633 return DeclPtrTy();
5634
John McCalldd4a3b02009-09-16 22:47:08 +00005635 D->setAccess(AS_public);
5636 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005637
John McCalldd4a3b02009-09-16 22:47:08 +00005638 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005639}
5640
John McCallbbbcdd92009-09-11 21:02:39 +00005641Sema::DeclPtrTy
5642Sema::ActOnFriendFunctionDecl(Scope *S,
5643 Declarator &D,
5644 bool IsDefinition,
5645 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005646 const DeclSpec &DS = D.getDeclSpec();
5647
5648 assert(DS.isFriendSpecified());
5649 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5650
5651 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005652 TypeSourceInfo *TInfo = 0;
5653 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005654
5655 // C++ [class.friend]p1
5656 // A friend of a class is a function or class....
5657 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005658 // It *doesn't* see through dependent types, which is correct
5659 // according to [temp.arg.type]p3:
5660 // If a declaration acquires a function type through a
5661 // type dependent on a template-parameter and this causes
5662 // a declaration that does not use the syntactic form of a
5663 // function declarator to have a function type, the program
5664 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005665 if (!T->isFunctionType()) {
5666 Diag(Loc, diag::err_unexpected_friend);
5667
5668 // It might be worthwhile to try to recover by creating an
5669 // appropriate declaration.
5670 return DeclPtrTy();
5671 }
5672
5673 // C++ [namespace.memdef]p3
5674 // - If a friend declaration in a non-local class first declares a
5675 // class or function, the friend class or function is a member
5676 // of the innermost enclosing namespace.
5677 // - The name of the friend is not found by simple name lookup
5678 // until a matching declaration is provided in that namespace
5679 // scope (either before or after the class declaration granting
5680 // friendship).
5681 // - If a friend function is called, its name may be found by the
5682 // name lookup that considers functions from namespaces and
5683 // classes associated with the types of the function arguments.
5684 // - When looking for a prior declaration of a class or a function
5685 // declared as a friend, scopes outside the innermost enclosing
5686 // namespace scope are not considered.
5687
John McCall02cace72009-08-28 07:59:38 +00005688 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5689 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005690 assert(Name);
5691
John McCall67d1a672009-08-06 02:15:43 +00005692 // The context we found the declaration in, or in which we should
5693 // create the declaration.
5694 DeclContext *DC;
5695
5696 // FIXME: handle local classes
5697
5698 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005699 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5700 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005701 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5702 DC = computeDeclContext(ScopeQual);
5703
5704 // FIXME: handle dependent contexts
5705 if (!DC) return DeclPtrTy();
John McCall77bb1aa2010-05-01 00:40:08 +00005706 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005707
John McCall68263142009-11-18 22:49:29 +00005708 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005709
5710 // If searching in that context implicitly found a declaration in
5711 // a different context, treat it like it wasn't found at all.
5712 // TODO: better diagnostics for this case. Suggesting the right
5713 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005714 // FIXME: getRepresentativeDecl() is not right here at all
5715 if (Previous.empty() ||
5716 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005717 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005718 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5719 return DeclPtrTy();
5720 }
5721
5722 // C++ [class.friend]p1: A friend of a class is a function or
5723 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005724 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005725 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5726
John McCall67d1a672009-08-06 02:15:43 +00005727 // Otherwise walk out to the nearest namespace scope looking for matches.
5728 } else {
5729 // TODO: handle local class contexts.
5730
5731 DC = CurContext;
5732 while (true) {
5733 // Skip class contexts. If someone can cite chapter and verse
5734 // for this behavior, that would be nice --- it's what GCC and
5735 // EDG do, and it seems like a reasonable intent, but the spec
5736 // really only says that checks for unqualified existing
5737 // declarations should stop at the nearest enclosing namespace,
5738 // not that they should only consider the nearest enclosing
5739 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005740 while (DC->isRecord())
5741 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005742
John McCall68263142009-11-18 22:49:29 +00005743 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005744
5745 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005746 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005747 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005748
John McCall67d1a672009-08-06 02:15:43 +00005749 if (DC->isFileContext()) break;
5750 DC = DC->getParent();
5751 }
5752
5753 // C++ [class.friend]p1: A friend of a class is a function or
5754 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005755 // C++0x changes this for both friend types and functions.
5756 // Most C++ 98 compilers do seem to give an error here, so
5757 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005758 if (!Previous.empty() && DC->Equals(CurContext)
5759 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005760 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5761 }
5762
Douglas Gregor182ddf02009-09-28 00:08:27 +00005763 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005764 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005765 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5766 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5767 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005768 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005769 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5770 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005771 return DeclPtrTy();
5772 }
John McCall67d1a672009-08-06 02:15:43 +00005773 }
5774
Douglas Gregor182ddf02009-09-28 00:08:27 +00005775 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005776 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005777 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005778 IsDefinition,
5779 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005780 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005781
Douglas Gregor182ddf02009-09-28 00:08:27 +00005782 assert(ND->getDeclContext() == DC);
5783 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005784
John McCallab88d972009-08-31 22:39:49 +00005785 // Add the function declaration to the appropriate lookup tables,
5786 // adjusting the redeclarations list as necessary. We don't
5787 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005788 //
John McCallab88d972009-08-31 22:39:49 +00005789 // Also update the scope-based lookup if the target context's
5790 // lookup context is in lexical scope.
5791 if (!CurContext->isDependentContext()) {
5792 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005793 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005794 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005795 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005796 }
John McCall02cace72009-08-28 07:59:38 +00005797
5798 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005799 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005800 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005801 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005802 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005803
Douglas Gregor182ddf02009-09-28 00:08:27 +00005804 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005805}
5806
Chris Lattnerb28317a2009-03-28 19:18:32 +00005807void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005808 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Chris Lattnerb28317a2009-03-28 19:18:32 +00005810 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005811 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5812 if (!Fn) {
5813 Diag(DelLoc, diag::err_deleted_non_function);
5814 return;
5815 }
5816 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5817 Diag(DelLoc, diag::err_deleted_decl_not_first);
5818 Diag(Prev->getLocation(), diag::note_previous_declaration);
5819 // If the declaration wasn't the first, we delete the function anyway for
5820 // recovery.
5821 }
5822 Fn->setDeleted();
5823}
Sebastian Redl13e88542009-04-27 21:33:24 +00005824
5825static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5826 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5827 ++CI) {
5828 Stmt *SubStmt = *CI;
5829 if (!SubStmt)
5830 continue;
5831 if (isa<ReturnStmt>(SubStmt))
5832 Self.Diag(SubStmt->getSourceRange().getBegin(),
5833 diag::err_return_in_constructor_handler);
5834 if (!isa<Expr>(SubStmt))
5835 SearchForReturnInStmt(Self, SubStmt);
5836 }
5837}
5838
5839void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5840 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5841 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5842 SearchForReturnInStmt(*this, Handler);
5843 }
5844}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005845
Mike Stump1eb44332009-09-09 15:08:12 +00005846bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005847 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005848 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5849 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005850
Chandler Carruth73857792010-02-15 11:53:20 +00005851 if (Context.hasSameType(NewTy, OldTy) ||
5852 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005853 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005854
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005855 // Check if the return types are covariant
5856 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005857
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005858 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005859 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5860 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005861 NewClassTy = NewPT->getPointeeType();
5862 OldClassTy = OldPT->getPointeeType();
5863 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005864 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5865 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5866 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5867 NewClassTy = NewRT->getPointeeType();
5868 OldClassTy = OldRT->getPointeeType();
5869 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005870 }
5871 }
Mike Stump1eb44332009-09-09 15:08:12 +00005872
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005873 // The return types aren't either both pointers or references to a class type.
5874 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005875 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005876 diag::err_different_return_type_for_overriding_virtual_function)
5877 << New->getDeclName() << NewTy << OldTy;
5878 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005879
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005880 return true;
5881 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005882
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005883 // C++ [class.virtual]p6:
5884 // If the return type of D::f differs from the return type of B::f, the
5885 // class type in the return type of D::f shall be complete at the point of
5886 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005887 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5888 if (!RT->isBeingDefined() &&
5889 RequireCompleteType(New->getLocation(), NewClassTy,
5890 PDiag(diag::err_covariant_return_incomplete)
5891 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005892 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005893 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005894
Douglas Gregora4923eb2009-11-16 21:35:15 +00005895 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005896 // Check if the new class derives from the old class.
5897 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5898 Diag(New->getLocation(),
5899 diag::err_covariant_return_not_derived)
5900 << New->getDeclName() << NewTy << OldTy;
5901 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5902 return true;
5903 }
Mike Stump1eb44332009-09-09 15:08:12 +00005904
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005905 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00005906 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00005907 diag::err_covariant_return_inaccessible_base,
5908 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5909 // FIXME: Should this point to the return type?
5910 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005911 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5912 return true;
5913 }
5914 }
Mike Stump1eb44332009-09-09 15:08:12 +00005915
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005916 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005917 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005918 Diag(New->getLocation(),
5919 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005920 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005921 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5922 return true;
5923 };
Mike Stump1eb44332009-09-09 15:08:12 +00005924
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005925
5926 // The new class type must have the same or less qualifiers as the old type.
5927 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5928 Diag(New->getLocation(),
5929 diag::err_covariant_return_type_class_type_more_qualified)
5930 << New->getDeclName() << NewTy << OldTy;
5931 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5932 return true;
5933 };
Mike Stump1eb44332009-09-09 15:08:12 +00005934
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005935 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005936}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005937
Sean Huntbbd37c62009-11-21 08:43:09 +00005938bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5939 const CXXMethodDecl *Old)
5940{
5941 if (Old->hasAttr<FinalAttr>()) {
5942 Diag(New->getLocation(), diag::err_final_function_overridden)
5943 << New->getDeclName();
5944 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5945 return true;
5946 }
5947
5948 return false;
5949}
5950
Douglas Gregor4ba31362009-12-01 17:24:26 +00005951/// \brief Mark the given method pure.
5952///
5953/// \param Method the method to be marked pure.
5954///
5955/// \param InitRange the source range that covers the "0" initializer.
5956bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5957 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5958 Method->setPure();
5959
5960 // A class is abstract if at least one function is pure virtual.
5961 Method->getParent()->setAbstract(true);
5962 return false;
5963 }
5964
5965 if (!Method->isInvalidDecl())
5966 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5967 << Method->getDeclName() << InitRange;
5968 return true;
5969}
5970
John McCall731ad842009-12-19 09:28:58 +00005971/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5972/// an initializer for the out-of-line declaration 'Dcl'. The scope
5973/// is a fresh scope pushed for just this purpose.
5974///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005975/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5976/// static data member of class X, names should be looked up in the scope of
5977/// class X.
5978void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005979 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005980 Decl *D = Dcl.getAs<Decl>();
5981 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005982
John McCall731ad842009-12-19 09:28:58 +00005983 // We should only get called for declarations with scope specifiers, like:
5984 // int foo::bar;
5985 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005986 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005987}
5988
5989/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005990/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005991void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005992 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005993 Decl *D = Dcl.getAs<Decl>();
5994 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005995
John McCall731ad842009-12-19 09:28:58 +00005996 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005997 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005998}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005999
6000/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6001/// C++ if/switch/while/for statement.
6002/// e.g: "if (int x = f()) {...}"
6003Action::DeclResult
6004Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
6005 // C++ 6.4p2:
6006 // The declarator shall not specify a function or an array.
6007 // The type-specifier-seq shall not contain typedef and shall not declare a
6008 // new class or enumeration.
6009 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6010 "Parser allowed 'typedef' as storage class of condition decl.");
6011
John McCalla93c9342009-12-07 02:54:59 +00006012 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006013 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00006014 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006015
6016 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6017 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6018 // would be created and CXXConditionDeclExpr wants a VarDecl.
6019 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6020 << D.getSourceRange();
6021 return DeclResult();
6022 } else if (OwnedTag && OwnedTag->isDefinition()) {
6023 // The type-specifier-seq shall not declare a new class or enumeration.
6024 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6025 }
6026
6027 DeclPtrTy Dcl = ActOnDeclarator(S, D);
6028 if (!Dcl)
6029 return DeclResult();
6030
6031 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
6032 VD->setDeclaredInCondition(true);
6033 return Dcl;
6034}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006035
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006036void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6037 bool DefinitionRequired) {
6038 // Ignore any vtable uses in unevaluated operands or for classes that do
6039 // not have a vtable.
6040 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6041 CurContext->isDependentContext() ||
6042 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006043 return;
6044
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006045 // Try to insert this class into the map.
6046 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6047 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6048 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6049 if (!Pos.second) {
6050 Pos.first->second = Pos.first->second || DefinitionRequired;
6051 return;
6052 }
6053
6054 // Local classes need to have their virtual members marked
6055 // immediately. For all other classes, we mark their virtual members
6056 // at the end of the translation unit.
6057 if (Class->isLocalClass())
6058 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006059 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006060 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006061}
6062
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006063bool Sema::DefineUsedVTables() {
6064 // If any dynamic classes have their key function defined within
6065 // this translation unit, then those vtables are considered "used" and must
6066 // be emitted.
6067 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6068 if (const CXXMethodDecl *KeyFunction
6069 = Context.getKeyFunction(DynamicClasses[I])) {
6070 const FunctionDecl *Definition = 0;
Douglas Gregorca4aa372010-05-14 04:08:48 +00006071 if (KeyFunction->getBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006072 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6073 }
6074 }
6075
6076 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006077 return false;
6078
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006079 // Note: The VTableUses vector could grow as a result of marking
6080 // the members of a class as "used", so we check the size each
6081 // time through the loop and prefer indices (with are stable) to
6082 // iterators (which are not).
6083 for (unsigned I = 0; I != VTableUses.size(); ++I) {
6084 CXXRecordDecl *Class
6085 = cast_or_null<CXXRecordDecl>(VTableUses[I].first)->getDefinition();
6086 if (!Class)
6087 continue;
6088
6089 SourceLocation Loc = VTableUses[I].second;
6090
6091 // If this class has a key function, but that key function is
6092 // defined in another translation unit, we don't need to emit the
6093 // vtable even though we're using it.
6094 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
6095 if (KeyFunction && !KeyFunction->getBody()) {
6096 switch (KeyFunction->getTemplateSpecializationKind()) {
6097 case TSK_Undeclared:
6098 case TSK_ExplicitSpecialization:
6099 case TSK_ExplicitInstantiationDeclaration:
6100 // The key function is in another translation unit.
6101 continue;
6102
6103 case TSK_ExplicitInstantiationDefinition:
6104 case TSK_ImplicitInstantiation:
6105 // We will be instantiating the key function.
6106 break;
6107 }
6108 } else if (!KeyFunction) {
6109 // If we have a class with no key function that is the subject
6110 // of an explicit instantiation declaration, suppress the
6111 // vtable; it will live with the explicit instantiation
6112 // definition.
6113 bool IsExplicitInstantiationDeclaration
6114 = Class->getTemplateSpecializationKind()
6115 == TSK_ExplicitInstantiationDeclaration;
6116 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6117 REnd = Class->redecls_end();
6118 R != REnd; ++R) {
6119 TemplateSpecializationKind TSK
6120 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6121 if (TSK == TSK_ExplicitInstantiationDeclaration)
6122 IsExplicitInstantiationDeclaration = true;
6123 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6124 IsExplicitInstantiationDeclaration = false;
6125 break;
6126 }
6127 }
6128
6129 if (IsExplicitInstantiationDeclaration)
6130 continue;
6131 }
6132
6133 // Mark all of the virtual members of this class as referenced, so
6134 // that we can build a vtable. Then, tell the AST consumer that a
6135 // vtable for this class is required.
6136 MarkVirtualMembersReferenced(Loc, Class);
6137 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6138 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6139
6140 // Optionally warn if we're emitting a weak vtable.
6141 if (Class->getLinkage() == ExternalLinkage &&
6142 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
6143 if (!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
6144 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6145 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006146 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006147 VTableUses.clear();
6148
Anders Carlssond6a637f2009-12-07 08:24:59 +00006149 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006150}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006151
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006152void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6153 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006154 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6155 e = RD->method_end(); i != e; ++i) {
6156 CXXMethodDecl *MD = *i;
6157
6158 // C++ [basic.def.odr]p2:
6159 // [...] A virtual member function is used if it is not pure. [...]
6160 if (MD->isVirtual() && !MD->isPure())
6161 MarkDeclarationReferenced(Loc, MD);
6162 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006163
6164 // Only classes that have virtual bases need a VTT.
6165 if (RD->getNumVBases() == 0)
6166 return;
6167
6168 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6169 e = RD->bases_end(); i != e; ++i) {
6170 const CXXRecordDecl *Base =
6171 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6172 if (i->isVirtual())
6173 continue;
6174 if (Base->getNumVBases() == 0)
6175 continue;
6176 MarkVirtualMembersReferenced(Loc, Base);
6177 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006178}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006179
6180/// SetIvarInitializers - This routine builds initialization ASTs for the
6181/// Objective-C implementation whose ivars need be initialized.
6182void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6183 if (!getLangOptions().CPlusPlus)
6184 return;
6185 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6186 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6187 CollectIvarsToConstructOrDestruct(OID, ivars);
6188 if (ivars.empty())
6189 return;
6190 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6191 for (unsigned i = 0; i < ivars.size(); i++) {
6192 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006193 if (Field->isInvalidDecl())
6194 continue;
6195
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006196 CXXBaseOrMemberInitializer *Member;
6197 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6198 InitializationKind InitKind =
6199 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6200
6201 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6202 Sema::OwningExprResult MemberInit =
6203 InitSeq.Perform(*this, InitEntity, InitKind,
6204 Sema::MultiExprArg(*this, 0, 0));
6205 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6206 // Note, MemberInit could actually come back empty if no initialization
6207 // is required (e.g., because it would call a trivial default constructor)
6208 if (!MemberInit.get() || MemberInit.isInvalid())
6209 continue;
6210
6211 Member =
6212 new (Context) CXXBaseOrMemberInitializer(Context,
6213 Field, SourceLocation(),
6214 SourceLocation(),
6215 MemberInit.takeAs<Expr>(),
6216 SourceLocation());
6217 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006218
6219 // Be sure that the destructor is accessible and is marked as referenced.
6220 if (const RecordType *RecordTy
6221 = Context.getBaseElementType(Field->getType())
6222 ->getAs<RecordType>()) {
6223 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
6224 if (CXXDestructorDecl *Destructor
6225 = const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
6226 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6227 CheckDestructorAccess(Field->getLocation(), Destructor,
6228 PDiag(diag::err_access_dtor_ivar)
6229 << Context.getBaseElementType(Field->getType()));
6230 }
6231 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006232 }
6233 ObjCImplementation->setIvarInitializers(Context,
6234 AllToInit.data(), AllToInit.size());
6235 }
6236}