blob: eb62b6a9dbf213e1a5e1d08b1c97cbec4c18901c [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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000093 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000138
John McCallb4eb64d2010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
Anders Carlsson0ece4912009-12-15 20:51:39 +0000140 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson9351c172009-08-25 03:18:48 +0000157 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000158}
159
Chris Lattner8123a952008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163void
John McCalld226f652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCalld226f652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177 return;
178 }
179
Anders Carlsson66e30672009-08-25 01:02:06 +0000180 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000181 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
182 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000183 Param->setInvalidDecl();
184 return;
185 }
Mike Stump1eb44332009-09-09 15:08:12 +0000186
John McCall9ae2f072010-08-23 23:25:46 +0000187 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000188}
189
Douglas Gregor61366e92008-12-24 00:01:03 +0000190/// ActOnParamUnparsedDefaultArgument - We've seen a default
191/// argument for a function parameter, but we can't parse it yet
192/// because we're inside a class definition. Note that this default
193/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000194void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 SourceLocation EqualLoc,
196 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
John McCalld226f652010-08-21 09:40:31 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000201 if (Param)
202 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000205}
206
Douglas Gregor72b505b2008-12-16 21:30:33 +0000207/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
208/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000209void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000210 if (!param)
211 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
John McCalld226f652010-08-21 09:40:31 +0000213 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Anders Carlsson5e300d12009-06-12 16:51:40 +0000215 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Anders Carlsson5e300d12009-06-12 16:51:40 +0000217 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000218}
219
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000220/// CheckExtraCXXDefaultArguments - Check for any extra default
221/// arguments in the declarator, which is not a function declaration
222/// or definition and therefore is not permitted to have default
223/// arguments. This routine should be invoked for every declarator
224/// that is not a function declaration or definition.
225void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
226 // C++ [dcl.fct.default]p3
227 // A default argument expression shall be specified only in the
228 // parameter-declaration-clause of a function declaration or in a
229 // template-parameter (14.1). It shall not be specified for a
230 // parameter pack. If it is specified in a
231 // parameter-declaration-clause, it shall not occur within a
232 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000234 DeclaratorChunk &chunk = D.getTypeObject(i);
235 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000236 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
237 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000238 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000239 if (Param->hasUnparsedDefaultArg()) {
240 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000241 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
242 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
243 delete Toks;
244 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000245 } else if (Param->getDefaultArg()) {
246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << Param->getDefaultArg()->getSourceRange();
248 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000249 }
250 }
251 }
252 }
253}
254
Chris Lattner3d1cee32008-04-08 05:04:30 +0000255// MergeCXXFunctionDecl - Merge two declarations of the same C++
256// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000257// type. Subroutine of MergeFunctionDecl. Returns true if there was an
258// error, false otherwise.
259bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
260 bool Invalid = false;
261
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000263 // For non-template functions, default arguments can be added in
264 // later declarations of a function in the same
265 // scope. Declarations in different scopes have completely
266 // distinct sets of default arguments. That is, declarations in
267 // inner scopes do not acquire default arguments from
268 // declarations in outer scopes, and vice versa. In a given
269 // function declaration, all parameters subsequent to a
270 // parameter with a default argument shall have default
271 // arguments supplied in this or previous declarations. A
272 // default argument shall not be redefined by a later
273 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000274 //
275 // C++ [dcl.fct.default]p6:
276 // Except for member functions of class templates, the default arguments
277 // in a member function definition that appears outside of the class
278 // definition are added to the set of default arguments provided by the
279 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000280 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
281 ParmVarDecl *OldParam = Old->getParamDecl(p);
282 ParmVarDecl *NewParam = New->getParamDecl(p);
283
Douglas Gregor6cc15182009-09-11 18:44:32 +0000284 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000285 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
286 // hint here. Alternatively, we could walk the type-source information
287 // for NewParam to find the last source location in the type... but it
288 // isn't worth the effort right now. This is the kind of test case that
289 // is hard to get right:
290
291 // int f(int);
292 // void g(int (*fp)(int) = f);
293 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000294 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000295 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000296 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000297
298 // Look for the function declaration where the default argument was
299 // actually written, which may be a declaration prior to Old.
300 for (FunctionDecl *Older = Old->getPreviousDeclaration();
301 Older; Older = Older->getPreviousDeclaration()) {
302 if (!Older->getParamDecl(p)->hasDefaultArg())
303 break;
304
305 OldParam = Older->getParamDecl(p);
306 }
307
308 Diag(OldParam->getLocation(), diag::note_previous_definition)
309 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000310 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000311 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000312 // Merge the old default argument into the new parameter.
313 // It's important to use getInit() here; getDefaultArg()
314 // strips off any top-level CXXExprWithTemporaries.
John McCallbf73b352010-03-12 18:31:32 +0000315 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000316 if (OldParam->hasUninstantiatedDefaultArg())
317 NewParam->setUninstantiatedDefaultArg(
318 OldParam->getUninstantiatedDefaultArg());
319 else
John McCall3d6c1782010-05-04 01:53:42 +0000320 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000321 } else if (NewParam->hasDefaultArg()) {
322 if (New->getDescribedFunctionTemplate()) {
323 // Paragraph 4, quoted above, only applies to non-template functions.
324 Diag(NewParam->getLocation(),
325 diag::err_param_default_argument_template_redecl)
326 << NewParam->getDefaultArgRange();
327 Diag(Old->getLocation(), diag::note_template_prev_declaration)
328 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000329 } else if (New->getTemplateSpecializationKind()
330 != TSK_ImplicitInstantiation &&
331 New->getTemplateSpecializationKind() != TSK_Undeclared) {
332 // C++ [temp.expr.spec]p21:
333 // Default function arguments shall not be specified in a declaration
334 // or a definition for one of the following explicit specializations:
335 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000336 // - the explicit specialization of a member function template;
337 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000338 // template where the class template specialization to which the
339 // member function specialization belongs is implicitly
340 // instantiated.
341 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
342 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
343 << New->getDeclName()
344 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000345 } else if (New->getDeclContext()->isDependentContext()) {
346 // C++ [dcl.fct.default]p6 (DR217):
347 // Default arguments for a member function of a class template shall
348 // be specified on the initial declaration of the member function
349 // within the class template.
350 //
351 // Reading the tea leaves a bit in DR217 and its reference to DR205
352 // leads me to the conclusion that one cannot add default function
353 // arguments for an out-of-line definition of a member function of a
354 // dependent type.
355 int WhichKind = 2;
356 if (CXXRecordDecl *Record
357 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
358 if (Record->getDescribedClassTemplate())
359 WhichKind = 0;
360 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
361 WhichKind = 1;
362 else
363 WhichKind = 2;
364 }
365
366 Diag(NewParam->getLocation(),
367 diag::err_param_default_argument_member_template_redecl)
368 << WhichKind
369 << NewParam->getDefaultArgRange();
370 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000371 }
372 }
373
Douglas Gregore13ad832010-02-12 07:32:17 +0000374 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000375 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000376
Douglas Gregorcda9c672009-02-16 17:45:42 +0000377 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378}
379
380/// CheckCXXDefaultArguments - Verify that the default arguments for a
381/// function declaration are well-formed according to C++
382/// [dcl.fct.default].
383void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
384 unsigned NumParams = FD->getNumParams();
385 unsigned p;
386
387 // Find first parameter with a default argument
388 for (p = 0; p < NumParams; ++p) {
389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000391 break;
392 }
393
394 // C++ [dcl.fct.default]p4:
395 // In a given function declaration, all parameters
396 // subsequent to a parameter with a default argument shall
397 // have default arguments supplied in this or previous
398 // declarations. A default argument shall not be redefined
399 // by a later declaration (not even to the same value).
400 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000401 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000403 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000404 if (Param->isInvalidDecl())
405 /* We already complained about this parameter. */;
406 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000407 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000408 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000409 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000410 else
Mike Stump1eb44332009-09-09 15:08:12 +0000411 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000412 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 LastMissingDefaultArg = p;
415 }
416 }
417
418 if (LastMissingDefaultArg > 0) {
419 // Some default arguments were missing. Clear out all of the
420 // default arguments up to (and including) the last missing
421 // default argument, so that we leave the function parameters
422 // in a semantically valid state.
423 for (p = 0; p <= LastMissingDefaultArg; ++p) {
424 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000425 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000426 Param->setDefaultArg(0);
427 }
428 }
429 }
430}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000431
Douglas Gregorb48fe382008-10-31 09:07:45 +0000432/// isCurrentClassName - Determine whether the identifier II is the
433/// name of the class type currently being defined. In the case of
434/// nested classes, this will only return true if II is the name of
435/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000436bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
437 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000438 assert(getLangOptions().CPlusPlus && "No class names in C!");
439
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000440 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000441 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000442 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000443 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
444 } else
445 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
446
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000447 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000448 return &II == CurDecl->getIdentifier();
449 else
450 return false;
451}
452
Mike Stump1eb44332009-09-09 15:08:12 +0000453/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000454///
455/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
456/// and returns NULL otherwise.
457CXXBaseSpecifier *
458Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
459 SourceRange SpecifierRange,
460 bool Virtual, AccessSpecifier Access,
Nick Lewycky56062202010-07-26 16:56:01 +0000461 TypeSourceInfo *TInfo) {
462 QualType BaseType = TInfo->getType();
463
Douglas Gregor2943aed2009-03-03 04:44:36 +0000464 // C++ [class.union]p1:
465 // A union shall not have base classes.
466 if (Class->isUnion()) {
467 Diag(Class->getLocation(), diag::err_base_clause_on_union)
468 << SpecifierRange;
469 return 0;
470 }
471
472 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000473 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000474 Class->getTagKind() == TTK_Class,
475 Access, TInfo);
476
477 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000478
479 // Base specifiers must be record types.
480 if (!BaseType->isRecordType()) {
481 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
482 return 0;
483 }
484
485 // C++ [class.union]p1:
486 // A union shall not be used as a base class.
487 if (BaseType->isUnionType()) {
488 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
489 return 0;
490 }
491
492 // C++ [class.derived]p2:
493 // The class-name in a base-specifier shall not be an incompletely
494 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000495 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000496 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000497 << SpecifierRange)) {
498 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499 return 0;
John McCall572fc622010-08-17 07:23:57 +0000500 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000501
Eli Friedman1d954f62009-08-15 21:55:26 +0000502 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000503 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000504 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000505 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000506 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000507 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
508 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000509
Sean Huntbbd37c62009-11-21 08:43:09 +0000510 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
511 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
512 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000513 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
514 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000515 return 0;
516 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000517
John McCall572fc622010-08-17 07:23:57 +0000518 if (BaseDecl->isInvalidDecl())
519 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000520
521 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000522 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000523 Class->getTagKind() == TTK_Class,
524 Access, TInfo);
Anders Carlsson51f94042009-12-03 17:49:57 +0000525}
526
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000527/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
528/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000529/// example:
530/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000531/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000532BaseResult
John McCalld226f652010-08-21 09:40:31 +0000533Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000534 bool Virtual, AccessSpecifier Access,
John McCallb3d87482010-08-24 05:47:05 +0000535 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000536 if (!classdecl)
537 return true;
538
Douglas Gregor40808ce2009-03-09 23:48:35 +0000539 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000541 if (!Class)
542 return true;
543
Nick Lewycky56062202010-07-26 16:56:01 +0000544 TypeSourceInfo *TInfo = 0;
545 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000546 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000547 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000548 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Douglas Gregor2943aed2009-03-03 04:44:36 +0000550 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000551}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000552
Douglas Gregor2943aed2009-03-03 04:44:36 +0000553/// \brief Performs the actual work of attaching the given base class
554/// specifiers to a C++ class.
555bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
556 unsigned NumBases) {
557 if (NumBases == 0)
558 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000559
560 // Used to keep track of which base types we have already seen, so
561 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000562 // that the key is always the unqualified canonical type of the base
563 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000564 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
565
566 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000567 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000569 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000570 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000572 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000573 if (!Class->hasObjectMember()) {
574 if (const RecordType *FDTTy =
575 NewBaseType.getTypePtr()->getAs<RecordType>())
576 if (FDTTy->getDecl()->hasObjectMember())
577 Class->setHasObjectMember(true);
578 }
579
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000580 if (KnownBaseTypes[NewBaseType]) {
581 // C++ [class.mi]p3:
582 // A class shall not be specified as a direct base class of a
583 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000584 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000585 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000586 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000587 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000588
589 // Delete the duplicate base class specifier; we're going to
590 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000591 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000592
593 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000594 } else {
595 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 KnownBaseTypes[NewBaseType] = Bases[idx];
597 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000598 }
599 }
600
601 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000602 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000603
604 // Delete the remaining (good) base class specifiers, since their
605 // data has been copied into the CXXRecordDecl.
606 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000607 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608
609 return Invalid;
610}
611
612/// ActOnBaseSpecifiers - Attach the given base specifiers to the
613/// class, after checking whether there are any duplicate base
614/// classes.
John McCalld226f652010-08-21 09:40:31 +0000615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 unsigned NumBases) {
617 if (!ClassDecl || !Bases || !NumBases)
618 return;
619
620 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000622 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000623}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000624
John McCall3cb0ebd2010-03-10 03:28:59 +0000625static CXXRecordDecl *GetClassForType(QualType T) {
626 if (const RecordType *RT = T->getAs<RecordType>())
627 return cast<CXXRecordDecl>(RT->getDecl());
628 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
629 return ICT->getDecl();
630 else
631 return 0;
632}
633
Douglas Gregora8f32e02009-10-06 17:59:45 +0000634/// \brief Determine whether the type \p Derived is a C++ class that is
635/// derived from the type \p Base.
636bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
637 if (!getLangOptions().CPlusPlus)
638 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000639
640 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
641 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000642 return false;
643
John McCall3cb0ebd2010-03-10 03:28:59 +0000644 CXXRecordDecl *BaseRD = GetClassForType(Base);
645 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000646 return false;
647
John McCall86ff3082010-02-04 22:26:26 +0000648 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
649 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000650}
651
652/// \brief Determine whether the type \p Derived is a C++ class that is
653/// derived from the type \p Base.
654bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
655 if (!getLangOptions().CPlusPlus)
656 return false;
657
John McCall3cb0ebd2010-03-10 03:28:59 +0000658 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
659 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000660 return false;
661
John McCall3cb0ebd2010-03-10 03:28:59 +0000662 CXXRecordDecl *BaseRD = GetClassForType(Base);
663 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000664 return false;
665
Douglas Gregora8f32e02009-10-06 17:59:45 +0000666 return DerivedRD->isDerivedFrom(BaseRD, Paths);
667}
668
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000669void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000670 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000671 assert(BasePathArray.empty() && "Base path array must be empty!");
672 assert(Paths.isRecordingPaths() && "Must record paths!");
673
674 const CXXBasePath &Path = Paths.front();
675
676 // We first go backward and check if we have a virtual base.
677 // FIXME: It would be better if CXXBasePath had the base specifier for
678 // the nearest virtual base.
679 unsigned Start = 0;
680 for (unsigned I = Path.size(); I != 0; --I) {
681 if (Path[I - 1].Base->isVirtual()) {
682 Start = I - 1;
683 break;
684 }
685 }
686
687 // Now add all bases.
688 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000690}
691
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000692/// \brief Determine whether the given base path includes a virtual
693/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000694bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
695 for (CXXCastPath::const_iterator B = BasePath.begin(),
696 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000697 B != BEnd; ++B)
698 if ((*B)->isVirtual())
699 return true;
700
701 return false;
702}
703
Douglas Gregora8f32e02009-10-06 17:59:45 +0000704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
705/// conversion (where Derived and Base are class types) is
706/// well-formed, meaning that the conversion is unambiguous (and
707/// that all of the base classes are accessible). Returns true
708/// and emits a diagnostic if the code is ill-formed, returns false
709/// otherwise. Loc is the location where this routine should point to
710/// if there is an error, and Range is the source range to highlight
711/// if there is an error.
712bool
713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000714 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715 unsigned AmbigiousBaseConvID,
716 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000717 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000718 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000719 // First, determine whether the path from Derived to Base is
720 // ambiguous. This is slightly more expensive than checking whether
721 // the Derived to Base conversion exists, because here we need to
722 // explore multiple paths to determine if there is an ambiguity.
723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
724 /*DetectVirtual=*/false);
725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
726 assert(DerivationOkay &&
727 "Can only be used with a derived-to-base conversion");
728 (void)DerivationOkay;
729
730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000731 if (InaccessibleBaseID) {
732 // Check that the base class can be accessed.
733 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
734 InaccessibleBaseID)) {
735 case AR_inaccessible:
736 return true;
737 case AR_accessible:
738 case AR_dependent:
739 case AR_delayed:
740 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000741 }
John McCall6b2accb2010-02-10 09:31:12 +0000742 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000743
744 // Build a base path if necessary.
745 if (BasePath)
746 BuildBasePathArray(Paths, *BasePath);
747 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000748 }
749
750 // We know that the derived-to-base conversion is ambiguous, and
751 // we're going to produce a diagnostic. Perform the derived-to-base
752 // search just one more time to compute all of the possible paths so
753 // that we can print them out. This is more expensive than any of
754 // the previous derived-to-base checks we've done, but at this point
755 // performance isn't as much of an issue.
756 Paths.clear();
757 Paths.setRecordingPaths(true);
758 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
759 assert(StillOkay && "Can only be used with a derived-to-base conversion");
760 (void)StillOkay;
761
762 // Build up a textual representation of the ambiguous paths, e.g.,
763 // D -> B -> A, that will be used to illustrate the ambiguous
764 // conversions in the diagnostic. We only print one of the paths
765 // to each base class subobject.
766 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
767
768 Diag(Loc, AmbigiousBaseConvID)
769 << Derived << Base << PathDisplayStr << Range << Name;
770 return true;
771}
772
773bool
774Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000775 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000776 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000777 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000778 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000779 IgnoreAccess ? 0
780 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000781 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000782 Loc, Range, DeclarationName(),
783 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000784}
785
786
787/// @brief Builds a string representing ambiguous paths from a
788/// specific derived class to different subobjects of the same base
789/// class.
790///
791/// This function builds a string that can be used in error messages
792/// to show the different paths that one can take through the
793/// inheritance hierarchy to go from the derived class to different
794/// subobjects of a base class. The result looks something like this:
795/// @code
796/// struct D -> struct B -> struct A
797/// struct D -> struct C -> struct A
798/// @endcode
799std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
800 std::string PathDisplayStr;
801 std::set<unsigned> DisplayedPaths;
802 for (CXXBasePaths::paths_iterator Path = Paths.begin();
803 Path != Paths.end(); ++Path) {
804 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
805 // We haven't displayed a path to this particular base
806 // class subobject yet.
807 PathDisplayStr += "\n ";
808 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
809 for (CXXBasePath::const_iterator Element = Path->begin();
810 Element != Path->end(); ++Element)
811 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
812 }
813 }
814
815 return PathDisplayStr;
816}
817
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000818//===----------------------------------------------------------------------===//
819// C++ class member Handling
820//===----------------------------------------------------------------------===//
821
Abramo Bagnara6206d532010-06-05 05:09:32 +0000822/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000823Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
824 SourceLocation ASLoc,
825 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000826 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000827 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000828 ASLoc, ColonLoc);
829 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000830 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000831}
832
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000833/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
834/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
835/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000836/// any.
John McCalld226f652010-08-21 09:40:31 +0000837Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000838Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000839 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000840 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
841 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000843 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
844 DeclarationName Name = NameInfo.getName();
845 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000846 Expr *BitWidth = static_cast<Expr*>(BW);
847 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000848
John McCall4bde1e12010-06-04 08:34:12 +0000849 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000850 assert(!DS.isFriendSpecified());
851
John McCall4bde1e12010-06-04 08:34:12 +0000852 bool isFunc = false;
853 if (D.isFunctionDeclarator())
854 isFunc = true;
855 else if (D.getNumTypeObjects() == 0 &&
856 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000857 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000858 isFunc = TDType->isFunctionType();
859 }
860
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000861 // C++ 9.2p6: A member shall not be declared to have automatic storage
862 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000863 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
864 // data members and cannot be applied to names declared const or static,
865 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000866 switch (DS.getStorageClassSpec()) {
867 case DeclSpec::SCS_unspecified:
868 case DeclSpec::SCS_typedef:
869 case DeclSpec::SCS_static:
870 // FALL THROUGH.
871 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000872 case DeclSpec::SCS_mutable:
873 if (isFunc) {
874 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000875 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000876 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000877 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Sebastian Redla11f42f2008-11-17 23:24:37 +0000879 // FIXME: It would be nicer if the keyword was ignored only for this
880 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000881 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000882 }
883 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884 default:
885 if (DS.getStorageClassSpecLoc().isValid())
886 Diag(DS.getStorageClassSpecLoc(),
887 diag::err_storageclass_invalid_for_member);
888 else
889 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
890 D.getMutableDeclSpec().ClearStorageClassSpecs();
891 }
892
Sebastian Redl669d5d72008-11-14 23:42:31 +0000893 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
894 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000895 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000896
897 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000898 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000899 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000900 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
901 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000902 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000903 } else {
John McCalld226f652010-08-21 09:40:31 +0000904 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000905 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000906 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000907 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000908
909 // Non-instance-fields can't have a bitfield.
910 if (BitWidth) {
911 if (Member->isInvalidDecl()) {
912 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000913 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000914 // C++ 9.6p3: A bit-field shall not be a static member.
915 // "static member 'A' cannot be a bit-field"
916 Diag(Loc, diag::err_static_not_bitfield)
917 << Name << BitWidth->getSourceRange();
918 } else if (isa<TypedefDecl>(Member)) {
919 // "typedef member 'x' cannot be a bit-field"
920 Diag(Loc, diag::err_typedef_not_bitfield)
921 << Name << BitWidth->getSourceRange();
922 } else {
923 // A function typedef ("typedef int f(); f a;").
924 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
925 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000926 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000927 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner8b963ef2009-03-05 23:01:03 +0000930 BitWidth = 0;
931 Member->setInvalidDecl();
932 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000933
934 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor37b372b2009-08-20 22:52:58 +0000936 // If we have declared a member function template, set the access of the
937 // templated declaration as well.
938 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
939 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000940 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000941
Douglas Gregor10bd3682008-11-17 22:58:34 +0000942 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000943
Douglas Gregor021c3b32009-03-11 23:00:04 +0000944 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +0000945 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000946 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +0000947 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000948
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000950 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +0000951 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000952 }
John McCalld226f652010-08-21 09:40:31 +0000953 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000954}
955
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000956/// \brief Find the direct and/or virtual base specifiers that
957/// correspond to the given base type, for use in base initialization
958/// within a constructor.
959static bool FindBaseInitializer(Sema &SemaRef,
960 CXXRecordDecl *ClassDecl,
961 QualType BaseType,
962 const CXXBaseSpecifier *&DirectBaseSpec,
963 const CXXBaseSpecifier *&VirtualBaseSpec) {
964 // First, check for a direct base class.
965 DirectBaseSpec = 0;
966 for (CXXRecordDecl::base_class_const_iterator Base
967 = ClassDecl->bases_begin();
968 Base != ClassDecl->bases_end(); ++Base) {
969 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
970 // We found a direct base of this type. That's what we're
971 // initializing.
972 DirectBaseSpec = &*Base;
973 break;
974 }
975 }
976
977 // Check for a virtual base class.
978 // FIXME: We might be able to short-circuit this if we know in advance that
979 // there are no virtual bases.
980 VirtualBaseSpec = 0;
981 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
982 // We haven't found a base yet; search the class hierarchy for a
983 // virtual base class.
984 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
985 /*DetectVirtual=*/false);
986 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
987 BaseType, Paths)) {
988 for (CXXBasePaths::paths_iterator Path = Paths.begin();
989 Path != Paths.end(); ++Path) {
990 if (Path->back().Base->isVirtual()) {
991 VirtualBaseSpec = Path->back().Base;
992 break;
993 }
994 }
995 }
996 }
997
998 return DirectBaseSpec || VirtualBaseSpec;
999}
1000
Douglas Gregor7ad83902008-11-05 04:29:56 +00001001/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001002MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001003Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001004 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001005 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001006 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001007 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001008 SourceLocation IdLoc,
1009 SourceLocation LParenLoc,
1010 ExprTy **Args, unsigned NumArgs,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001011 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001012 if (!ConstructorD)
1013 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001015 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
1017 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001018 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001019 if (!Constructor) {
1020 // The user wrote a constructor initializer on a function that is
1021 // not a C++ constructor. Ignore the error for now, because we may
1022 // have more member initializers coming; we'll diagnose it just
1023 // once in ActOnMemInitializers.
1024 return true;
1025 }
1026
1027 CXXRecordDecl *ClassDecl = Constructor->getParent();
1028
1029 // C++ [class.base.init]p2:
1030 // Names in a mem-initializer-id are looked up in the scope of the
1031 // constructor’s class and, if not found in that scope, are looked
1032 // up in the scope containing the constructor’s
1033 // definition. [Note: if the constructor’s class contains a member
1034 // with the same name as a direct or virtual base class of the
1035 // class, a mem-initializer-id naming the member or base class and
1036 // composed of a single identifier refers to the class member. A
1037 // mem-initializer-id for the hidden base class may be specified
1038 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001039 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001040 // Look for a member, first.
1041 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001042 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001043 = ClassDecl->lookup(MemberOrBase);
1044 if (Result.first != Result.second)
1045 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001046
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001047 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001048
Eli Friedman59c04372009-07-29 19:44:27 +00001049 if (Member)
1050 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001051 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001052 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001053 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001054 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001055 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001056
1057 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001058 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001059 } else {
1060 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1061 LookupParsedName(R, S, &SS);
1062
1063 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1064 if (!TyD) {
1065 if (R.isAmbiguous()) return true;
1066
John McCallfd225442010-04-09 19:01:14 +00001067 // We don't want access-control diagnostics here.
1068 R.suppressDiagnostics();
1069
Douglas Gregor7a886e12010-01-19 06:46:48 +00001070 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1071 bool NotUnknownSpecialization = false;
1072 DeclContext *DC = computeDeclContext(SS, false);
1073 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1074 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1075
1076 if (!NotUnknownSpecialization) {
1077 // When the scope specifier can refer to a member of an unknown
1078 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001079 BaseType = CheckTypenameType(ETK_None,
1080 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001081 *MemberOrBase, SourceLocation(),
1082 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001083 if (BaseType.isNull())
1084 return true;
1085
Douglas Gregor7a886e12010-01-19 06:46:48 +00001086 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001087 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001088 }
1089 }
1090
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001091 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001092 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001093 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1094 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001095 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001096 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001097 // We have found a non-static data member with a similar
1098 // name to what was typed; complain and initialize that
1099 // member.
1100 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1101 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001102 << FixItHint::CreateReplacement(R.getNameLoc(),
1103 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001104 Diag(Member->getLocation(), diag::note_previous_decl)
1105 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001106
1107 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1108 LParenLoc, RParenLoc);
1109 }
1110 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1111 const CXXBaseSpecifier *DirectBaseSpec;
1112 const CXXBaseSpecifier *VirtualBaseSpec;
1113 if (FindBaseInitializer(*this, ClassDecl,
1114 Context.getTypeDeclType(Type),
1115 DirectBaseSpec, VirtualBaseSpec)) {
1116 // We have found a direct or virtual base class with a
1117 // similar name to what was typed; complain and initialize
1118 // that base class.
1119 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1120 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001121 << FixItHint::CreateReplacement(R.getNameLoc(),
1122 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001123
1124 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1125 : VirtualBaseSpec;
1126 Diag(BaseSpec->getSourceRange().getBegin(),
1127 diag::note_base_class_specified_here)
1128 << BaseSpec->getType()
1129 << BaseSpec->getSourceRange();
1130
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001131 TyD = Type;
1132 }
1133 }
1134 }
1135
Douglas Gregor7a886e12010-01-19 06:46:48 +00001136 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001137 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1138 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1139 return true;
1140 }
John McCall2b194412009-12-21 10:41:20 +00001141 }
1142
Douglas Gregor7a886e12010-01-19 06:46:48 +00001143 if (BaseType.isNull()) {
1144 BaseType = Context.getTypeDeclType(TyD);
1145 if (SS.isSet()) {
1146 NestedNameSpecifier *Qualifier =
1147 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001148
Douglas Gregor7a886e12010-01-19 06:46:48 +00001149 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001150 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001151 }
John McCall2b194412009-12-21 10:41:20 +00001152 }
1153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154
John McCalla93c9342009-12-07 02:54:59 +00001155 if (!TInfo)
1156 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001157
John McCalla93c9342009-12-07 02:54:59 +00001158 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001159 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001160}
1161
John McCallb4190042009-11-04 23:02:40 +00001162/// Checks an initializer expression for use of uninitialized fields, such as
1163/// containing the field that is being initialized. Returns true if there is an
1164/// uninitialized field was used an updates the SourceLocation parameter; false
1165/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001166static bool InitExprContainsUninitializedFields(const Stmt *S,
1167 const FieldDecl *LhsField,
1168 SourceLocation *L) {
1169 if (isa<CallExpr>(S)) {
1170 // Do not descend into function calls or constructors, as the use
1171 // of an uninitialized field may be valid. One would have to inspect
1172 // the contents of the function/ctor to determine if it is safe or not.
1173 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1174 // may be safe, depending on what the function/ctor does.
1175 return false;
1176 }
1177 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1178 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001179
1180 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1181 // The member expression points to a static data member.
1182 assert(VD->isStaticDataMember() &&
1183 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001184 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001185 return false;
1186 }
1187
1188 if (isa<EnumConstantDecl>(RhsField)) {
1189 // The member expression points to an enum.
1190 return false;
1191 }
1192
John McCallb4190042009-11-04 23:02:40 +00001193 if (RhsField == LhsField) {
1194 // Initializing a field with itself. Throw a warning.
1195 // But wait; there are exceptions!
1196 // Exception #1: The field may not belong to this record.
1197 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001198 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001199 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1200 // Even though the field matches, it does not belong to this record.
1201 return false;
1202 }
1203 // None of the exceptions triggered; return true to indicate an
1204 // uninitialized field was used.
1205 *L = ME->getMemberLoc();
1206 return true;
1207 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001208 } else if (isa<SizeOfAlignOfExpr>(S)) {
1209 // sizeof/alignof doesn't reference contents, do not warn.
1210 return false;
1211 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1212 // address-of doesn't reference contents (the pointer may be dereferenced
1213 // in the same expression but it would be rare; and weird).
1214 if (UOE->getOpcode() == UO_AddrOf)
1215 return false;
John McCallb4190042009-11-04 23:02:40 +00001216 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001217 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1218 it != e; ++it) {
1219 if (!*it) {
1220 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001221 continue;
1222 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001223 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1224 return true;
John McCallb4190042009-11-04 23:02:40 +00001225 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001226 return false;
John McCallb4190042009-11-04 23:02:40 +00001227}
1228
John McCallf312b1e2010-08-26 23:41:50 +00001229MemInitResult
Eli Friedman59c04372009-07-29 19:44:27 +00001230Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1231 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001232 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001233 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001234 // Diagnose value-uses of fields to initialize themselves, e.g.
1235 // foo(foo)
1236 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001237 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001238 for (unsigned i = 0; i < NumArgs; ++i) {
1239 SourceLocation L;
1240 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1241 // FIXME: Return true in the case when other fields are used before being
1242 // uninitialized. For example, let this field be the i'th field. When
1243 // initializing the i'th field, throw a warning if any of the >= i'th
1244 // fields are used, as they are not yet initialized.
1245 // Right now we are only handling the case where the i'th field uses
1246 // itself in its initializer.
1247 Diag(L, diag::warn_field_is_uninit);
1248 }
1249 }
1250
Eli Friedman59c04372009-07-29 19:44:27 +00001251 bool HasDependentArg = false;
1252 for (unsigned i = 0; i < NumArgs; i++)
1253 HasDependentArg |= Args[i]->isTypeDependent();
1254
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001255 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001256 // Can't check initialization for a member of dependent type or when
1257 // any of the arguments are type-dependent expressions.
John McCall9ae2f072010-08-23 23:25:46 +00001258 Expr *Init
1259 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1260 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001261
1262 // Erase any temporaries within this evaluation context; we're not
1263 // going to track them in the AST, since we'll be rebuilding the
1264 // ASTs during template instantiation.
1265 ExprTemporaries.erase(
1266 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1267 ExprTemporaries.end());
1268
1269 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1270 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001271 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001272 RParenLoc);
1273
Douglas Gregor7ad83902008-11-05 04:29:56 +00001274 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001275
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001276 if (Member->isInvalidDecl())
1277 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001278
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001279 // Initialize the member.
1280 InitializedEntity MemberEntity =
1281 InitializedEntity::InitializeMember(Member, 0);
1282 InitializationKind Kind =
1283 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1284
1285 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1286
John McCall60d7b3a2010-08-24 06:29:42 +00001287 ExprResult MemberInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001288 InitSeq.Perform(*this, MemberEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001289 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001290 if (MemberInit.isInvalid())
1291 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001292
1293 CheckImplicitConversions(MemberInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001294
1295 // C++0x [class.base.init]p7:
1296 // The initialization of each base and member constitutes a
1297 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001298 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001299 if (MemberInit.isInvalid())
1300 return true;
1301
1302 // If we are in a dependent context, template instantiation will
1303 // perform this type-checking again. Just save the arguments that we
1304 // received in a ParenListExpr.
1305 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1306 // of the information that we have about the member
1307 // initializer. However, deconstructing the ASTs is a dicey process,
1308 // and this approach is far more likely to get the corner cases right.
1309 if (CurContext->isDependentContext()) {
1310 // Bump the reference count of all of the arguments.
1311 for (unsigned I = 0; I != NumArgs; ++I)
1312 Args[I]->Retain();
1313
John McCall9ae2f072010-08-23 23:25:46 +00001314 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1315 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001316 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1317 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001318 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001319 RParenLoc);
1320 }
1321
Douglas Gregor802ab452009-12-02 22:36:29 +00001322 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001323 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001324 MemberInit.get(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001325 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001326}
1327
John McCallf312b1e2010-08-26 23:41:50 +00001328MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001329Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001330 Expr **Args, unsigned NumArgs,
1331 SourceLocation LParenLoc, SourceLocation RParenLoc,
1332 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001333 bool HasDependentArg = false;
1334 for (unsigned i = 0; i < NumArgs; i++)
1335 HasDependentArg |= Args[i]->isTypeDependent();
1336
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001337 SourceLocation BaseLoc
1338 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1339
1340 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1341 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1342 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1343
1344 // C++ [class.base.init]p2:
1345 // [...] Unless the mem-initializer-id names a nonstatic data
1346 // member of the constructor’s class or a direct or virtual base
1347 // of that class, the mem-initializer is ill-formed. A
1348 // mem-initializer-list can initialize a base class using any
1349 // name that denotes that base class type.
1350 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1351
1352 // Check for direct and virtual base classes.
1353 const CXXBaseSpecifier *DirectBaseSpec = 0;
1354 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1355 if (!Dependent) {
1356 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1357 VirtualBaseSpec);
1358
1359 // C++ [base.class.init]p2:
1360 // Unless the mem-initializer-id names a nonstatic data member of the
1361 // constructor's class or a direct or virtual base of that class, the
1362 // mem-initializer is ill-formed.
1363 if (!DirectBaseSpec && !VirtualBaseSpec) {
1364 // If the class has any dependent bases, then it's possible that
1365 // one of those types will resolve to the same type as
1366 // BaseType. Therefore, just treat this as a dependent base
1367 // class initialization. FIXME: Should we try to check the
1368 // initialization anyway? It seems odd.
1369 if (ClassDecl->hasAnyDependentBases())
1370 Dependent = true;
1371 else
1372 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1373 << BaseType << Context.getTypeDeclType(ClassDecl)
1374 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1375 }
1376 }
1377
1378 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001379 // Can't check initialization for a base of dependent type or when
1380 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001381 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001382 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1383 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001384
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001385 // Erase any temporaries within this evaluation context; we're not
1386 // going to track them in the AST, since we'll be rebuilding the
1387 // ASTs during template instantiation.
1388 ExprTemporaries.erase(
1389 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1390 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001392 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001393 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001394 LParenLoc,
1395 BaseInit.takeAs<Expr>(),
1396 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001397 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001398
1399 // C++ [base.class.init]p2:
1400 // If a mem-initializer-id is ambiguous because it designates both
1401 // a direct non-virtual base class and an inherited virtual base
1402 // class, the mem-initializer is ill-formed.
1403 if (DirectBaseSpec && VirtualBaseSpec)
1404 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001405 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001406
1407 CXXBaseSpecifier *BaseSpec
1408 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1409 if (!BaseSpec)
1410 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1411
1412 // Initialize the base.
1413 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001414 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001415 InitializationKind Kind =
1416 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1417
1418 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1419
John McCall60d7b3a2010-08-24 06:29:42 +00001420 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001421 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001422 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001423 if (BaseInit.isInvalid())
1424 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001425
1426 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001427
1428 // C++0x [class.base.init]p7:
1429 // The initialization of each base and member constitutes a
1430 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001431 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001432 if (BaseInit.isInvalid())
1433 return true;
1434
1435 // If we are in a dependent context, template instantiation will
1436 // perform this type-checking again. Just save the arguments that we
1437 // received in a ParenListExpr.
1438 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1439 // of the information that we have about the base
1440 // initializer. However, deconstructing the ASTs is a dicey process,
1441 // and this approach is far more likely to get the corner cases right.
1442 if (CurContext->isDependentContext()) {
1443 // Bump the reference count of all of the arguments.
1444 for (unsigned I = 0; I != NumArgs; ++I)
1445 Args[I]->Retain();
1446
John McCall60d7b3a2010-08-24 06:29:42 +00001447 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001448 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1449 RParenLoc));
1450 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001451 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001452 LParenLoc,
1453 Init.takeAs<Expr>(),
1454 RParenLoc);
1455 }
1456
1457 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001458 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001459 LParenLoc,
1460 BaseInit.takeAs<Expr>(),
1461 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001462}
1463
Anders Carlssone5ef7402010-04-23 03:10:23 +00001464/// ImplicitInitializerKind - How an implicit base or member initializer should
1465/// initialize its base or member.
1466enum ImplicitInitializerKind {
1467 IIK_Default,
1468 IIK_Copy,
1469 IIK_Move
1470};
1471
Anders Carlssondefefd22010-04-23 02:00:02 +00001472static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001473BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001474 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001475 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001476 bool IsInheritedVirtualBase,
1477 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001478 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001479 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1480 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001481
John McCall60d7b3a2010-08-24 06:29:42 +00001482 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001483
1484 switch (ImplicitInitKind) {
1485 case IIK_Default: {
1486 InitializationKind InitKind
1487 = InitializationKind::CreateDefault(Constructor->getLocation());
1488 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1489 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001490 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001491 break;
1492 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001493
Anders Carlssone5ef7402010-04-23 03:10:23 +00001494 case IIK_Copy: {
1495 ParmVarDecl *Param = Constructor->getParamDecl(0);
1496 QualType ParamType = Param->getType().getNonReferenceType();
1497
1498 Expr *CopyCtorArg =
1499 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001500 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001501
Anders Carlssonc7957502010-04-24 22:02:54 +00001502 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001503 QualType ArgTy =
1504 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1505 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001506
1507 CXXCastPath BasePath;
1508 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001509 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001510 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001511 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001512
Anders Carlssone5ef7402010-04-23 03:10:23 +00001513 InitializationKind InitKind
1514 = InitializationKind::CreateDirect(Constructor->getLocation(),
1515 SourceLocation(), SourceLocation());
1516 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1517 &CopyCtorArg, 1);
1518 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001519 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001520 break;
1521 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001522
Anders Carlssone5ef7402010-04-23 03:10:23 +00001523 case IIK_Move:
1524 assert(false && "Unhandled initializer kind!");
1525 }
John McCall9ae2f072010-08-23 23:25:46 +00001526
1527 if (BaseInit.isInvalid())
1528 return true;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001529
John McCall9ae2f072010-08-23 23:25:46 +00001530 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlsson84688f22010-04-20 23:11:20 +00001531 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001532 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001533
Anders Carlssondefefd22010-04-23 02:00:02 +00001534 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001535 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1536 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1537 SourceLocation()),
1538 BaseSpec->isVirtual(),
1539 SourceLocation(),
1540 BaseInit.takeAs<Expr>(),
1541 SourceLocation());
1542
Anders Carlssondefefd22010-04-23 02:00:02 +00001543 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001544}
1545
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001546static bool
1547BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001548 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001549 FieldDecl *Field,
1550 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001551 if (Field->isInvalidDecl())
1552 return true;
1553
Chandler Carruthf186b542010-06-29 23:50:44 +00001554 SourceLocation Loc = Constructor->getLocation();
1555
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001556 if (ImplicitInitKind == IIK_Copy) {
1557 ParmVarDecl *Param = Constructor->getParamDecl(0);
1558 QualType ParamType = Param->getType().getNonReferenceType();
1559
1560 Expr *MemberExprBase =
1561 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001562 Loc, ParamType, 0);
1563
1564 // Build a reference to this field within the parameter.
1565 CXXScopeSpec SS;
1566 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1567 Sema::LookupMemberName);
1568 MemberLookup.addDecl(Field, AS_public);
1569 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001570 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001571 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001572 ParamType, Loc,
1573 /*IsArrow=*/false,
1574 SS,
1575 /*FirstQualifierInScope=*/0,
1576 MemberLookup,
1577 /*TemplateArgs=*/0);
1578 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001579 return true;
1580
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001581 // When the field we are copying is an array, create index variables for
1582 // each dimension of the array. We use these index variables to subscript
1583 // the source array, and other clients (e.g., CodeGen) will perform the
1584 // necessary iteration with these index variables.
1585 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1586 QualType BaseType = Field->getType();
1587 QualType SizeType = SemaRef.Context.getSizeType();
1588 while (const ConstantArrayType *Array
1589 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1590 // Create the iteration variable for this array index.
1591 IdentifierInfo *IterationVarName = 0;
1592 {
1593 llvm::SmallString<8> Str;
1594 llvm::raw_svector_ostream OS(Str);
1595 OS << "__i" << IndexVariables.size();
1596 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1597 }
1598 VarDecl *IterationVar
1599 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1600 IterationVarName, SizeType,
1601 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001602 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001603 IndexVariables.push_back(IterationVar);
1604
1605 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001606 ExprResult IterationVarRef
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001607 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1608 assert(!IterationVarRef.isInvalid() &&
1609 "Reference to invented variable cannot fail!");
1610
1611 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001612 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001613 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001614 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001615 Loc);
1616 if (CopyCtorArg.isInvalid())
1617 return true;
1618
1619 BaseType = Array->getElementType();
1620 }
1621
1622 // Construct the entity that we will be initializing. For an array, this
1623 // will be first element in the array, which may require several levels
1624 // of array-subscript entities.
1625 llvm::SmallVector<InitializedEntity, 4> Entities;
1626 Entities.reserve(1 + IndexVariables.size());
1627 Entities.push_back(InitializedEntity::InitializeMember(Field));
1628 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1629 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1630 0,
1631 Entities.back()));
1632
1633 // Direct-initialize to use the copy constructor.
1634 InitializationKind InitKind =
1635 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1636
1637 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1638 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1639 &CopyCtorArgE, 1);
1640
John McCall60d7b3a2010-08-24 06:29:42 +00001641 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001642 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001643 MultiExprArg(&CopyCtorArgE, 1));
John McCall9ae2f072010-08-23 23:25:46 +00001644 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001645 if (MemberInit.isInvalid())
1646 return true;
1647
1648 CXXMemberInit
1649 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1650 MemberInit.takeAs<Expr>(), Loc,
1651 IndexVariables.data(),
1652 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001653 return false;
1654 }
1655
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001656 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1657
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001658 QualType FieldBaseElementType =
1659 SemaRef.Context.getBaseElementType(Field->getType());
1660
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001661 if (FieldBaseElementType->isRecordType()) {
1662 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001663 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001664 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001665
1666 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001667 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001668 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001669 if (MemberInit.isInvalid())
1670 return true;
1671
1672 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001673 if (MemberInit.isInvalid())
1674 return true;
1675
1676 CXXMemberInit =
1677 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001678 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001679 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001680 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001681 return false;
1682 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001683
1684 if (FieldBaseElementType->isReferenceType()) {
1685 SemaRef.Diag(Constructor->getLocation(),
1686 diag::err_uninitialized_member_in_ctor)
1687 << (int)Constructor->isImplicit()
1688 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1689 << 0 << Field->getDeclName();
1690 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1691 return true;
1692 }
1693
1694 if (FieldBaseElementType.isConstQualified()) {
1695 SemaRef.Diag(Constructor->getLocation(),
1696 diag::err_uninitialized_member_in_ctor)
1697 << (int)Constructor->isImplicit()
1698 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1699 << 1 << Field->getDeclName();
1700 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1701 return true;
1702 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001703
1704 // Nothing to initialize.
1705 CXXMemberInit = 0;
1706 return false;
1707}
John McCallf1860e52010-05-20 23:23:51 +00001708
1709namespace {
1710struct BaseAndFieldInfo {
1711 Sema &S;
1712 CXXConstructorDecl *Ctor;
1713 bool AnyErrorsInInits;
1714 ImplicitInitializerKind IIK;
1715 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1716 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1717
1718 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1719 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1720 // FIXME: Handle implicit move constructors.
1721 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1722 IIK = IIK_Copy;
1723 else
1724 IIK = IIK_Default;
1725 }
1726};
1727}
1728
Chandler Carruthe861c602010-06-30 02:59:29 +00001729static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1730 FieldDecl *Top, FieldDecl *Field,
1731 CXXBaseOrMemberInitializer *Init) {
1732 // If the member doesn't need to be initialized, Init will still be null.
1733 if (!Init)
1734 return;
1735
1736 Info.AllToInit.push_back(Init);
1737 if (Field != Top) {
1738 Init->setMember(Top);
1739 Init->setAnonUnionMember(Field);
1740 }
1741}
1742
John McCallf1860e52010-05-20 23:23:51 +00001743static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1744 FieldDecl *Top, FieldDecl *Field) {
1745
Chandler Carruthe861c602010-06-30 02:59:29 +00001746 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001747 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruthe861c602010-06-30 02:59:29 +00001748 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001749 return false;
1750 }
1751
1752 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1753 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1754 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001755 CXXRecordDecl *FieldClassDecl
1756 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001757
1758 // Even though union members never have non-trivial default
1759 // constructions in C++03, we still build member initializers for aggregate
1760 // record types which can be union members, and C++0x allows non-trivial
1761 // default constructors for union members, so we ensure that only one
1762 // member is initialized for these.
1763 if (FieldClassDecl->isUnion()) {
1764 // First check for an explicit initializer for one field.
1765 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1766 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1767 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1768 RecordFieldInitializer(Info, Top, *FA, Init);
1769
1770 // Once we've initialized a field of an anonymous union, the union
1771 // field in the class is also initialized, so exit immediately.
1772 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001773 } else if ((*FA)->isAnonymousStructOrUnion()) {
1774 if (CollectFieldInitializer(Info, Top, *FA))
1775 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001776 }
1777 }
1778
1779 // Fallthrough and construct a default initializer for the union as
1780 // a whole, which can call its default constructor if such a thing exists
1781 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1782 // behavior going forward with C++0x, when anonymous unions there are
1783 // finalized, we should revisit this.
1784 } else {
1785 // For structs, we simply descend through to initialize all members where
1786 // necessary.
1787 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1788 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1789 if (CollectFieldInitializer(Info, Top, *FA))
1790 return true;
1791 }
1792 }
John McCallf1860e52010-05-20 23:23:51 +00001793 }
1794
1795 // Don't try to build an implicit initializer if there were semantic
1796 // errors in any of the initializers (and therefore we might be
1797 // missing some that the user actually wrote).
1798 if (Info.AnyErrorsInInits)
1799 return false;
1800
1801 CXXBaseOrMemberInitializer *Init = 0;
1802 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1803 return true;
John McCallf1860e52010-05-20 23:23:51 +00001804
Chandler Carruthe861c602010-06-30 02:59:29 +00001805 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001806 return false;
1807}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001808
Eli Friedman80c30da2009-11-09 19:20:36 +00001809bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001810Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001811 CXXBaseOrMemberInitializer **Initializers,
1812 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001813 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001814 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001815 // Just store the initializers as written, they will be checked during
1816 // instantiation.
1817 if (NumInitializers > 0) {
1818 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1819 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1820 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1821 memcpy(baseOrMemberInitializers, Initializers,
1822 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1823 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1824 }
1825
1826 return false;
1827 }
1828
John McCallf1860e52010-05-20 23:23:51 +00001829 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001830
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001831 // We need to build the initializer AST according to order of construction
1832 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001833 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001834 if (!ClassDecl)
1835 return true;
1836
Eli Friedman80c30da2009-11-09 19:20:36 +00001837 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001839 for (unsigned i = 0; i < NumInitializers; i++) {
1840 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001841
1842 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001843 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001844 else
John McCallf1860e52010-05-20 23:23:51 +00001845 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001846 }
1847
Anders Carlsson711f34a2010-04-21 19:52:01 +00001848 // Keep track of the direct virtual bases.
1849 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1850 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1851 E = ClassDecl->bases_end(); I != E; ++I) {
1852 if (I->isVirtual())
1853 DirectVBases.insert(I);
1854 }
1855
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001856 // Push virtual bases before others.
1857 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1858 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1859
1860 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001861 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1862 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001863 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001864 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001865 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001866 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001867 VBase, IsInheritedVirtualBase,
1868 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001869 HadError = true;
1870 continue;
1871 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001872
John McCallf1860e52010-05-20 23:23:51 +00001873 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001874 }
1875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
John McCallf1860e52010-05-20 23:23:51 +00001877 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001878 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1879 E = ClassDecl->bases_end(); Base != E; ++Base) {
1880 // Virtuals are in the virtual base list and already constructed.
1881 if (Base->isVirtual())
1882 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001884 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001885 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1886 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001887 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001888 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001889 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001890 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001891 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001892 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001893 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001894 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001895
John McCallf1860e52010-05-20 23:23:51 +00001896 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001897 }
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
John McCallf1860e52010-05-20 23:23:51 +00001900 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001901 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001902 E = ClassDecl->field_end(); Field != E; ++Field) {
1903 if ((*Field)->getType()->isIncompleteArrayType()) {
1904 assert(ClassDecl->hasFlexibleArrayMember() &&
1905 "Incomplete array type is not valid");
1906 continue;
1907 }
John McCallf1860e52010-05-20 23:23:51 +00001908 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001909 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001910 }
Mike Stump1eb44332009-09-09 15:08:12 +00001911
John McCallf1860e52010-05-20 23:23:51 +00001912 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001913 if (NumInitializers > 0) {
1914 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1915 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1916 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001917 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001918 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001919 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001920
John McCallef027fe2010-03-16 21:39:52 +00001921 // Constructors implicitly reference the base and member
1922 // destructors.
1923 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1924 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001925 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001926
1927 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001928}
1929
Eli Friedman6347f422009-07-21 19:28:10 +00001930static void *GetKeyForTopLevelField(FieldDecl *Field) {
1931 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001932 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001933 if (RT->getDecl()->isAnonymousStructOrUnion())
1934 return static_cast<void *>(RT->getDecl());
1935 }
1936 return static_cast<void *>(Field);
1937}
1938
Anders Carlssonea356fb2010-04-02 05:42:15 +00001939static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1940 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001941}
1942
Anders Carlssonea356fb2010-04-02 05:42:15 +00001943static void *GetKeyForMember(ASTContext &Context,
1944 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001945 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001946 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001947 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001948
Eli Friedman6347f422009-07-21 19:28:10 +00001949 // For fields injected into the class via declaration of an anonymous union,
1950 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001951 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001953 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1954 // data member of the class. Data member used in the initializer list is
1955 // in AnonUnionMember field.
1956 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1957 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001958
John McCall3c3ccdb2010-04-10 09:28:51 +00001959 // If the field is a member of an anonymous struct or union, our key
1960 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001961 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001962 if (RD->isAnonymousStructOrUnion()) {
1963 while (true) {
1964 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1965 if (Parent->isAnonymousStructOrUnion())
1966 RD = Parent;
1967 else
1968 break;
1969 }
1970
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001971 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001974 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001975}
1976
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001977static void
1978DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001979 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001980 CXXBaseOrMemberInitializer **Inits,
1981 unsigned NumInits) {
1982 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001983 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001984
John McCalld6ca8da2010-04-10 07:37:23 +00001985 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1986 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001987 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001988
John McCalld6ca8da2010-04-10 07:37:23 +00001989 // Build the list of bases and members in the order that they'll
1990 // actually be initialized. The explicit initializers should be in
1991 // this same order but may be missing things.
1992 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Anders Carlsson071d6102010-04-02 03:38:04 +00001994 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1995
John McCalld6ca8da2010-04-10 07:37:23 +00001996 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001997 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001998 ClassDecl->vbases_begin(),
1999 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002000 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002001
John McCalld6ca8da2010-04-10 07:37:23 +00002002 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002003 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002004 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002005 if (Base->isVirtual())
2006 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002007 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCalld6ca8da2010-04-10 07:37:23 +00002010 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002011 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2012 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002013 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002014
John McCalld6ca8da2010-04-10 07:37:23 +00002015 unsigned NumIdealInits = IdealInitKeys.size();
2016 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002017
John McCalld6ca8da2010-04-10 07:37:23 +00002018 CXXBaseOrMemberInitializer *PrevInit = 0;
2019 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2020 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2021 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2022
2023 // Scan forward to try to find this initializer in the idealized
2024 // initializers list.
2025 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2026 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002027 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002028
2029 // If we didn't find this initializer, it must be because we
2030 // scanned past it on a previous iteration. That can only
2031 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002032 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002033 Sema::SemaDiagnosticBuilder D =
2034 SemaRef.Diag(PrevInit->getSourceLocation(),
2035 diag::warn_initializer_out_of_order);
2036
2037 if (PrevInit->isMemberInitializer())
2038 D << 0 << PrevInit->getMember()->getDeclName();
2039 else
2040 D << 1 << PrevInit->getBaseClassInfo()->getType();
2041
2042 if (Init->isMemberInitializer())
2043 D << 0 << Init->getMember()->getDeclName();
2044 else
2045 D << 1 << Init->getBaseClassInfo()->getType();
2046
2047 // Move back to the initializer's location in the ideal list.
2048 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2049 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002050 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002051
2052 assert(IdealIndex != NumIdealInits &&
2053 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002054 }
John McCalld6ca8da2010-04-10 07:37:23 +00002055
2056 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002057 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002058}
2059
John McCall3c3ccdb2010-04-10 09:28:51 +00002060namespace {
2061bool CheckRedundantInit(Sema &S,
2062 CXXBaseOrMemberInitializer *Init,
2063 CXXBaseOrMemberInitializer *&PrevInit) {
2064 if (!PrevInit) {
2065 PrevInit = Init;
2066 return false;
2067 }
2068
2069 if (FieldDecl *Field = Init->getMember())
2070 S.Diag(Init->getSourceLocation(),
2071 diag::err_multiple_mem_initialization)
2072 << Field->getDeclName()
2073 << Init->getSourceRange();
2074 else {
2075 Type *BaseClass = Init->getBaseClass();
2076 assert(BaseClass && "neither field nor base");
2077 S.Diag(Init->getSourceLocation(),
2078 diag::err_multiple_base_initialization)
2079 << QualType(BaseClass, 0)
2080 << Init->getSourceRange();
2081 }
2082 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2083 << 0 << PrevInit->getSourceRange();
2084
2085 return true;
2086}
2087
2088typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2089typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2090
2091bool CheckRedundantUnionInit(Sema &S,
2092 CXXBaseOrMemberInitializer *Init,
2093 RedundantUnionMap &Unions) {
2094 FieldDecl *Field = Init->getMember();
2095 RecordDecl *Parent = Field->getParent();
2096 if (!Parent->isAnonymousStructOrUnion())
2097 return false;
2098
2099 NamedDecl *Child = Field;
2100 do {
2101 if (Parent->isUnion()) {
2102 UnionEntry &En = Unions[Parent];
2103 if (En.first && En.first != Child) {
2104 S.Diag(Init->getSourceLocation(),
2105 diag::err_multiple_mem_union_initialization)
2106 << Field->getDeclName()
2107 << Init->getSourceRange();
2108 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2109 << 0 << En.second->getSourceRange();
2110 return true;
2111 } else if (!En.first) {
2112 En.first = Child;
2113 En.second = Init;
2114 }
2115 }
2116
2117 Child = Parent;
2118 Parent = cast<RecordDecl>(Parent->getDeclContext());
2119 } while (Parent->isAnonymousStructOrUnion());
2120
2121 return false;
2122}
2123}
2124
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002125/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002126void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002127 SourceLocation ColonLoc,
2128 MemInitTy **meminits, unsigned NumMemInits,
2129 bool AnyErrors) {
2130 if (!ConstructorDecl)
2131 return;
2132
2133 AdjustDeclIfTemplate(ConstructorDecl);
2134
2135 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002136 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002137
2138 if (!Constructor) {
2139 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2140 return;
2141 }
2142
2143 CXXBaseOrMemberInitializer **MemInits =
2144 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002145
2146 // Mapping for the duplicate initializers check.
2147 // For member initializers, this is keyed with a FieldDecl*.
2148 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002149 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002150
2151 // Mapping for the inconsistent anonymous-union initializers check.
2152 RedundantUnionMap MemberUnions;
2153
Anders Carlssonea356fb2010-04-02 05:42:15 +00002154 bool HadError = false;
2155 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002156 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002157
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002158 // Set the source order index.
2159 Init->setSourceOrder(i);
2160
John McCall3c3ccdb2010-04-10 09:28:51 +00002161 if (Init->isMemberInitializer()) {
2162 FieldDecl *Field = Init->getMember();
2163 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2164 CheckRedundantUnionInit(*this, Init, MemberUnions))
2165 HadError = true;
2166 } else {
2167 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2168 if (CheckRedundantInit(*this, Init, Members[Key]))
2169 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002170 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002171 }
2172
Anders Carlssonea356fb2010-04-02 05:42:15 +00002173 if (HadError)
2174 return;
2175
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002176 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002177
2178 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002179}
2180
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002181void
John McCallef027fe2010-03-16 21:39:52 +00002182Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2183 CXXRecordDecl *ClassDecl) {
2184 // Ignore dependent contexts.
2185 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002186 return;
John McCall58e6f342010-03-16 05:22:47 +00002187
2188 // FIXME: all the access-control diagnostics are positioned on the
2189 // field/base declaration. That's probably good; that said, the
2190 // user might reasonably want to know why the destructor is being
2191 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002192
Anders Carlsson9f853df2009-11-17 04:44:12 +00002193 // Non-static data members.
2194 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2195 E = ClassDecl->field_end(); I != E; ++I) {
2196 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002197 if (Field->isInvalidDecl())
2198 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002199 QualType FieldType = Context.getBaseElementType(Field->getType());
2200
2201 const RecordType* RT = FieldType->getAs<RecordType>();
2202 if (!RT)
2203 continue;
2204
2205 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2206 if (FieldClassDecl->hasTrivialDestructor())
2207 continue;
2208
Douglas Gregordb89f282010-07-01 22:47:18 +00002209 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002210 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002211 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002212 << Field->getDeclName()
2213 << FieldType);
2214
John McCallef027fe2010-03-16 21:39:52 +00002215 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002216 }
2217
John McCall58e6f342010-03-16 05:22:47 +00002218 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2219
Anders Carlsson9f853df2009-11-17 04:44:12 +00002220 // Bases.
2221 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2222 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002223 // Bases are always records in a well-formed non-dependent class.
2224 const RecordType *RT = Base->getType()->getAs<RecordType>();
2225
2226 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002227 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002228 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002229
2230 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002231 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002232 if (BaseClassDecl->hasTrivialDestructor())
2233 continue;
John McCall58e6f342010-03-16 05:22:47 +00002234
Douglas Gregordb89f282010-07-01 22:47:18 +00002235 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002236
2237 // FIXME: caret should be on the start of the class name
2238 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002239 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002240 << Base->getType()
2241 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002242
John McCallef027fe2010-03-16 21:39:52 +00002243 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002244 }
2245
2246 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002247 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2248 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002249
2250 // Bases are always records in a well-formed non-dependent class.
2251 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2252
2253 // Ignore direct virtual bases.
2254 if (DirectVirtualBases.count(RT))
2255 continue;
2256
Anders Carlsson9f853df2009-11-17 04:44:12 +00002257 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002258 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002259 if (BaseClassDecl->hasTrivialDestructor())
2260 continue;
John McCall58e6f342010-03-16 05:22:47 +00002261
Douglas Gregordb89f282010-07-01 22:47:18 +00002262 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002263 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002264 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002265 << VBase->getType());
2266
John McCallef027fe2010-03-16 21:39:52 +00002267 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002268 }
2269}
2270
John McCalld226f652010-08-21 09:40:31 +00002271void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002272 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002273 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Mike Stump1eb44332009-09-09 15:08:12 +00002275 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002276 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002277 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002278}
2279
Mike Stump1eb44332009-09-09 15:08:12 +00002280bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002281 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002282 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002283 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002284 else
John McCall94c3b562010-08-18 09:41:07 +00002285 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002286}
2287
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002288bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002289 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002290 if (!getLangOptions().CPlusPlus)
2291 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Anders Carlsson11f21a02009-03-23 19:10:31 +00002293 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002294 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Ted Kremenek6217b802009-07-29 21:53:49 +00002296 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002297 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002298 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002299 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002301 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002302 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002303 }
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Ted Kremenek6217b802009-07-29 21:53:49 +00002305 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002306 if (!RT)
2307 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002308
John McCall86ff3082010-02-04 22:26:26 +00002309 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002310
John McCall94c3b562010-08-18 09:41:07 +00002311 // We can't answer whether something is abstract until it has a
2312 // definition. If it's currently being defined, we'll walk back
2313 // over all the declarations when we have a full definition.
2314 const CXXRecordDecl *Def = RD->getDefinition();
2315 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002316 return false;
2317
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002318 if (!RD->isAbstract())
2319 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002321 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002322 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002323
John McCall94c3b562010-08-18 09:41:07 +00002324 return true;
2325}
2326
2327void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2328 // Check if we've already emitted the list of pure virtual functions
2329 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002330 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002331 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002333 CXXFinalOverriderMap FinalOverriders;
2334 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002336 // Keep a set of seen pure methods so we won't diagnose the same method
2337 // more than once.
2338 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2339
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002340 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2341 MEnd = FinalOverriders.end();
2342 M != MEnd;
2343 ++M) {
2344 for (OverridingMethods::iterator SO = M->second.begin(),
2345 SOEnd = M->second.end();
2346 SO != SOEnd; ++SO) {
2347 // C++ [class.abstract]p4:
2348 // A class is abstract if it contains or inherits at least one
2349 // pure virtual function for which the final overrider is pure
2350 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002352 //
2353 if (SO->second.size() != 1)
2354 continue;
2355
2356 if (!SO->second.front().Method->isPure())
2357 continue;
2358
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002359 if (!SeenPureMethods.insert(SO->second.front().Method))
2360 continue;
2361
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002362 Diag(SO->second.front().Method->getLocation(),
2363 diag::note_pure_virtual_function)
2364 << SO->second.front().Method->getDeclName();
2365 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002366 }
2367
2368 if (!PureVirtualClassDiagSet)
2369 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2370 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002371}
2372
Anders Carlsson8211eff2009-03-24 01:19:16 +00002373namespace {
John McCall94c3b562010-08-18 09:41:07 +00002374struct AbstractUsageInfo {
2375 Sema &S;
2376 CXXRecordDecl *Record;
2377 CanQualType AbstractType;
2378 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002379
John McCall94c3b562010-08-18 09:41:07 +00002380 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2381 : S(S), Record(Record),
2382 AbstractType(S.Context.getCanonicalType(
2383 S.Context.getTypeDeclType(Record))),
2384 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002385
John McCall94c3b562010-08-18 09:41:07 +00002386 void DiagnoseAbstractType() {
2387 if (Invalid) return;
2388 S.DiagnoseAbstractType(Record);
2389 Invalid = true;
2390 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002391
John McCall94c3b562010-08-18 09:41:07 +00002392 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2393};
2394
2395struct CheckAbstractUsage {
2396 AbstractUsageInfo &Info;
2397 const NamedDecl *Ctx;
2398
2399 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2400 : Info(Info), Ctx(Ctx) {}
2401
2402 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2403 switch (TL.getTypeLocClass()) {
2404#define ABSTRACT_TYPELOC(CLASS, PARENT)
2405#define TYPELOC(CLASS, PARENT) \
2406 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2407#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002408 }
John McCall94c3b562010-08-18 09:41:07 +00002409 }
Mike Stump1eb44332009-09-09 15:08:12 +00002410
John McCall94c3b562010-08-18 09:41:07 +00002411 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2412 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2413 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2414 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2415 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002416 }
John McCall94c3b562010-08-18 09:41:07 +00002417 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002418
John McCall94c3b562010-08-18 09:41:07 +00002419 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2420 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2421 }
Mike Stump1eb44332009-09-09 15:08:12 +00002422
John McCall94c3b562010-08-18 09:41:07 +00002423 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2424 // Visit the type parameters from a permissive context.
2425 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2426 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2427 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2428 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2429 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2430 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002431 }
John McCall94c3b562010-08-18 09:41:07 +00002432 }
Mike Stump1eb44332009-09-09 15:08:12 +00002433
John McCall94c3b562010-08-18 09:41:07 +00002434 // Visit pointee types from a permissive context.
2435#define CheckPolymorphic(Type) \
2436 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2437 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2438 }
2439 CheckPolymorphic(PointerTypeLoc)
2440 CheckPolymorphic(ReferenceTypeLoc)
2441 CheckPolymorphic(MemberPointerTypeLoc)
2442 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002443
John McCall94c3b562010-08-18 09:41:07 +00002444 /// Handle all the types we haven't given a more specific
2445 /// implementation for above.
2446 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2447 // Every other kind of type that we haven't called out already
2448 // that has an inner type is either (1) sugar or (2) contains that
2449 // inner type in some way as a subobject.
2450 if (TypeLoc Next = TL.getNextTypeLoc())
2451 return Visit(Next, Sel);
2452
2453 // If there's no inner type and we're in a permissive context,
2454 // don't diagnose.
2455 if (Sel == Sema::AbstractNone) return;
2456
2457 // Check whether the type matches the abstract type.
2458 QualType T = TL.getType();
2459 if (T->isArrayType()) {
2460 Sel = Sema::AbstractArrayType;
2461 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002462 }
John McCall94c3b562010-08-18 09:41:07 +00002463 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2464 if (CT != Info.AbstractType) return;
2465
2466 // It matched; do some magic.
2467 if (Sel == Sema::AbstractArrayType) {
2468 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2469 << T << TL.getSourceRange();
2470 } else {
2471 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2472 << Sel << T << TL.getSourceRange();
2473 }
2474 Info.DiagnoseAbstractType();
2475 }
2476};
2477
2478void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2479 Sema::AbstractDiagSelID Sel) {
2480 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2481}
2482
2483}
2484
2485/// Check for invalid uses of an abstract type in a method declaration.
2486static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2487 CXXMethodDecl *MD) {
2488 // No need to do the check on definitions, which require that
2489 // the return/param types be complete.
2490 if (MD->isThisDeclarationADefinition())
2491 return;
2492
2493 // For safety's sake, just ignore it if we don't have type source
2494 // information. This should never happen for non-implicit methods,
2495 // but...
2496 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2497 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2498}
2499
2500/// Check for invalid uses of an abstract type within a class definition.
2501static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2502 CXXRecordDecl *RD) {
2503 for (CXXRecordDecl::decl_iterator
2504 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2505 Decl *D = *I;
2506 if (D->isImplicit()) continue;
2507
2508 // Methods and method templates.
2509 if (isa<CXXMethodDecl>(D)) {
2510 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2511 } else if (isa<FunctionTemplateDecl>(D)) {
2512 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2513 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2514
2515 // Fields and static variables.
2516 } else if (isa<FieldDecl>(D)) {
2517 FieldDecl *FD = cast<FieldDecl>(D);
2518 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2519 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2520 } else if (isa<VarDecl>(D)) {
2521 VarDecl *VD = cast<VarDecl>(D);
2522 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2523 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2524
2525 // Nested classes and class templates.
2526 } else if (isa<CXXRecordDecl>(D)) {
2527 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2528 } else if (isa<ClassTemplateDecl>(D)) {
2529 CheckAbstractClassUsage(Info,
2530 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2531 }
2532 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002533}
2534
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002535/// \brief Perform semantic checks on a class definition that has been
2536/// completing, introducing implicitly-declared members, checking for
2537/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002538void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002539 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002540 return;
2541
John McCall94c3b562010-08-18 09:41:07 +00002542 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2543 AbstractUsageInfo Info(*this, Record);
2544 CheckAbstractClassUsage(Info, Record);
2545 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002546
2547 // If this is not an aggregate type and has no user-declared constructor,
2548 // complain about any non-static data members of reference or const scalar
2549 // type, since they will never get initializers.
2550 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2551 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2552 bool Complained = false;
2553 for (RecordDecl::field_iterator F = Record->field_begin(),
2554 FEnd = Record->field_end();
2555 F != FEnd; ++F) {
2556 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002557 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002558 if (!Complained) {
2559 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2560 << Record->getTagKind() << Record;
2561 Complained = true;
2562 }
2563
2564 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2565 << F->getType()->isReferenceType()
2566 << F->getDeclName();
2567 }
2568 }
2569 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002570
2571 if (Record->isDynamicClass())
2572 DynamicClasses.push_back(Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002573}
2574
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002575void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002576 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002577 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002578 SourceLocation RBrac,
2579 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002580 if (!TagDecl)
2581 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Douglas Gregor42af25f2009-05-11 19:58:34 +00002583 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002584
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002585 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002586 // strict aliasing violation!
2587 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002588 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002589
Douglas Gregor23c94db2010-07-02 17:43:08 +00002590 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002591 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002592}
2593
Douglas Gregord92ec472010-07-01 05:10:53 +00002594namespace {
2595 /// \brief Helper class that collects exception specifications for
2596 /// implicitly-declared special member functions.
2597 class ImplicitExceptionSpecification {
2598 ASTContext &Context;
2599 bool AllowsAllExceptions;
2600 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2601 llvm::SmallVector<QualType, 4> Exceptions;
2602
2603 public:
2604 explicit ImplicitExceptionSpecification(ASTContext &Context)
2605 : Context(Context), AllowsAllExceptions(false) { }
2606
2607 /// \brief Whether the special member function should have any
2608 /// exception specification at all.
2609 bool hasExceptionSpecification() const {
2610 return !AllowsAllExceptions;
2611 }
2612
2613 /// \brief Whether the special member function should have a
2614 /// throw(...) exception specification (a Microsoft extension).
2615 bool hasAnyExceptionSpecification() const {
2616 return false;
2617 }
2618
2619 /// \brief The number of exceptions in the exception specification.
2620 unsigned size() const { return Exceptions.size(); }
2621
2622 /// \brief The set of exceptions in the exception specification.
2623 const QualType *data() const { return Exceptions.data(); }
2624
2625 /// \brief Note that
2626 void CalledDecl(CXXMethodDecl *Method) {
2627 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002628 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002629 return;
2630
2631 const FunctionProtoType *Proto
2632 = Method->getType()->getAs<FunctionProtoType>();
2633
2634 // If this function can throw any exceptions, make a note of that.
2635 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2636 AllowsAllExceptions = true;
2637 ExceptionsSeen.clear();
2638 Exceptions.clear();
2639 return;
2640 }
2641
2642 // Record the exceptions in this function's exception specification.
2643 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2644 EEnd = Proto->exception_end();
2645 E != EEnd; ++E)
2646 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2647 Exceptions.push_back(*E);
2648 }
2649 };
2650}
2651
2652
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002653/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2654/// special functions, such as the default constructor, copy
2655/// constructor, or destructor, to the given C++ class (C++
2656/// [special]p1). This routine can only be executed just before the
2657/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002658void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002659 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002660 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002661
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002662 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002663 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002664
Douglas Gregora376d102010-07-02 21:50:04 +00002665 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2666 ++ASTContext::NumImplicitCopyAssignmentOperators;
2667
2668 // If we have a dynamic class, then the copy assignment operator may be
2669 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2670 // it shows up in the right place in the vtable and that we diagnose
2671 // problems with the implicit exception specification.
2672 if (ClassDecl->isDynamicClass())
2673 DeclareImplicitCopyAssignment(ClassDecl);
2674 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002675
Douglas Gregor4923aa22010-07-02 20:37:36 +00002676 if (!ClassDecl->hasUserDeclaredDestructor()) {
2677 ++ASTContext::NumImplicitDestructors;
2678
2679 // If we have a dynamic class, then the destructor may be virtual, so we
2680 // have to declare the destructor immediately. This ensures that, e.g., it
2681 // shows up in the right place in the vtable and that we diagnose problems
2682 // with the implicit exception specification.
2683 if (ClassDecl->isDynamicClass())
2684 DeclareImplicitDestructor(ClassDecl);
2685 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002686}
2687
John McCalld226f652010-08-21 09:40:31 +00002688void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002689 if (!D)
2690 return;
2691
2692 TemplateParameterList *Params = 0;
2693 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2694 Params = Template->getTemplateParameters();
2695 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2696 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2697 Params = PartialSpec->getTemplateParameters();
2698 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002699 return;
2700
Douglas Gregor6569d682009-05-27 23:11:45 +00002701 for (TemplateParameterList::iterator Param = Params->begin(),
2702 ParamEnd = Params->end();
2703 Param != ParamEnd; ++Param) {
2704 NamedDecl *Named = cast<NamedDecl>(*Param);
2705 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002706 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002707 IdResolver.AddDecl(Named);
2708 }
2709 }
2710}
2711
John McCalld226f652010-08-21 09:40:31 +00002712void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002713 if (!RecordD) return;
2714 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002715 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002716 PushDeclContext(S, Record);
2717}
2718
John McCalld226f652010-08-21 09:40:31 +00002719void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002720 if (!RecordD) return;
2721 PopDeclContext();
2722}
2723
Douglas Gregor72b505b2008-12-16 21:30:33 +00002724/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2725/// parsing a top-level (non-nested) C++ class, and we are now
2726/// parsing those parts of the given Method declaration that could
2727/// not be parsed earlier (C++ [class.mem]p2), such as default
2728/// arguments. This action should enter the scope of the given
2729/// Method declaration as if we had just parsed the qualified method
2730/// name. However, it should not bring the parameters into scope;
2731/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002732void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002733}
2734
2735/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2736/// C++ method declaration. We're (re-)introducing the given
2737/// function parameter into scope for use in parsing later parts of
2738/// the method declaration. For example, we could see an
2739/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002740void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002741 if (!ParamD)
2742 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002743
John McCalld226f652010-08-21 09:40:31 +00002744 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002745
2746 // If this parameter has an unparsed default argument, clear it out
2747 // to make way for the parsed default argument.
2748 if (Param->hasUnparsedDefaultArg())
2749 Param->setDefaultArg(0);
2750
John McCalld226f652010-08-21 09:40:31 +00002751 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002752 if (Param->getDeclName())
2753 IdResolver.AddDecl(Param);
2754}
2755
2756/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2757/// processing the delayed method declaration for Method. The method
2758/// declaration is now considered finished. There may be a separate
2759/// ActOnStartOfFunctionDef action later (not necessarily
2760/// immediately!) for this method, if it was also defined inside the
2761/// class body.
John McCalld226f652010-08-21 09:40:31 +00002762void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002763 if (!MethodD)
2764 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002766 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002767
John McCalld226f652010-08-21 09:40:31 +00002768 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002769
2770 // Now that we have our default arguments, check the constructor
2771 // again. It could produce additional diagnostics or affect whether
2772 // the class has implicitly-declared destructors, among other
2773 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002774 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2775 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002776
2777 // Check the default arguments, which we may have added.
2778 if (!Method->isInvalidDecl())
2779 CheckCXXDefaultArguments(Method);
2780}
2781
Douglas Gregor42a552f2008-11-05 20:51:48 +00002782/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002783/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002784/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002785/// emit diagnostics and set the invalid bit to true. In any case, the type
2786/// will be updated to reflect a well-formed type for the constructor and
2787/// returned.
2788QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002789 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002790 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002791
2792 // C++ [class.ctor]p3:
2793 // A constructor shall not be virtual (10.3) or static (9.4). A
2794 // constructor can be invoked for a const, volatile or const
2795 // volatile object. A constructor shall not be declared const,
2796 // volatile, or const volatile (9.3.2).
2797 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002798 if (!D.isInvalidType())
2799 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2800 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2801 << SourceRange(D.getIdentifierLoc());
2802 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002803 }
John McCalld931b082010-08-26 03:08:43 +00002804 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002805 if (!D.isInvalidType())
2806 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2807 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2808 << SourceRange(D.getIdentifierLoc());
2809 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002810 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002811 }
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Chris Lattner65401802009-04-25 08:28:21 +00002813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2814 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002815 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2817 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002818 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2820 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002821 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2823 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002824 }
Mike Stump1eb44332009-09-09 15:08:12 +00002825
Douglas Gregor42a552f2008-11-05 20:51:48 +00002826 // Rebuild the function type "R" without any type qualifiers (in
2827 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002828 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002829 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002830 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2831 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002832 Proto->isVariadic(), 0,
2833 Proto->hasExceptionSpec(),
2834 Proto->hasAnyExceptionSpec(),
2835 Proto->getNumExceptions(),
2836 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002837 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002838}
2839
Douglas Gregor72b505b2008-12-16 21:30:33 +00002840/// CheckConstructor - Checks a fully-formed constructor for
2841/// well-formedness, issuing any diagnostics required. Returns true if
2842/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002843void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002844 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002845 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2846 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002847 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002848
2849 // C++ [class.copy]p3:
2850 // A declaration of a constructor for a class X is ill-formed if
2851 // its first parameter is of type (optionally cv-qualified) X and
2852 // either there are no other parameters or else all other
2853 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002854 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002855 ((Constructor->getNumParams() == 1) ||
2856 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002857 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2858 Constructor->getTemplateSpecializationKind()
2859 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002860 QualType ParamType = Constructor->getParamDecl(0)->getType();
2861 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2862 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002863 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002864 const char *ConstRef
2865 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2866 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002867 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002868 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002869
2870 // FIXME: Rather that making the constructor invalid, we should endeavor
2871 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002872 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002873 }
2874 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002875}
2876
John McCall15442822010-08-04 01:04:25 +00002877/// CheckDestructor - Checks a fully-formed destructor definition for
2878/// well-formedness, issuing any diagnostics required. Returns true
2879/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002880bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002881 CXXRecordDecl *RD = Destructor->getParent();
2882
2883 if (Destructor->isVirtual()) {
2884 SourceLocation Loc;
2885
2886 if (!Destructor->isImplicit())
2887 Loc = Destructor->getLocation();
2888 else
2889 Loc = RD->getLocation();
2890
2891 // If we have a virtual destructor, look up the deallocation function
2892 FunctionDecl *OperatorDelete = 0;
2893 DeclarationName Name =
2894 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002895 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002896 return true;
John McCall5efd91a2010-07-03 18:33:00 +00002897
2898 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00002899
2900 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002901 }
Anders Carlsson37909802009-11-30 21:24:50 +00002902
2903 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002904}
2905
Mike Stump1eb44332009-09-09 15:08:12 +00002906static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002907FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2908 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2909 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00002910 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002911}
2912
Douglas Gregor42a552f2008-11-05 20:51:48 +00002913/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2914/// the well-formednes of the destructor declarator @p D with type @p
2915/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002916/// emit diagnostics and set the declarator to invalid. Even if this happens,
2917/// will be updated to reflect a well-formed type for the destructor and
2918/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00002919QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002920 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002921 // C++ [class.dtor]p1:
2922 // [...] A typedef-name that names a class is a class-name
2923 // (7.1.3); however, a typedef-name that names a class shall not
2924 // be used as the identifier in the declarator for a destructor
2925 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002926 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00002927 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00002928 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002929 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002930
2931 // C++ [class.dtor]p2:
2932 // A destructor is used to destroy objects of its class type. A
2933 // destructor takes no parameters, and no return type can be
2934 // specified for it (not even void). The address of a destructor
2935 // shall not be taken. A destructor shall not be static. A
2936 // destructor can be invoked for a const, volatile or const
2937 // volatile object. A destructor shall not be declared const,
2938 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00002939 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002940 if (!D.isInvalidType())
2941 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2942 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00002943 << SourceRange(D.getIdentifierLoc())
2944 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2945
John McCalld931b082010-08-26 03:08:43 +00002946 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002947 }
Chris Lattner65401802009-04-25 08:28:21 +00002948 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002949 // Destructors don't have return types, but the parser will
2950 // happily parse something like:
2951 //
2952 // class X {
2953 // float ~X();
2954 // };
2955 //
2956 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002957 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2958 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2959 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002960 }
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Chris Lattner65401802009-04-25 08:28:21 +00002962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2963 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002964 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002965 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2966 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002967 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002968 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2969 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002970 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002971 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2972 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002973 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002974 }
2975
2976 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002977 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002978 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2979
2980 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002981 FTI.freeArgs();
2982 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002983 }
2984
Mike Stump1eb44332009-09-09 15:08:12 +00002985 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002986 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002987 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002988 D.setInvalidType();
2989 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002990
2991 // Rebuild the function type "R" without any type qualifiers or
2992 // parameters (in case any of the errors above fired) and with
2993 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00002994 // types.
2995 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2996 if (!Proto)
2997 return QualType();
2998
Douglas Gregorce056bc2010-02-21 22:15:06 +00002999 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003000 Proto->hasExceptionSpec(),
3001 Proto->hasAnyExceptionSpec(),
3002 Proto->getNumExceptions(),
3003 Proto->exception_begin(),
3004 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003005}
3006
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003007/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3008/// well-formednes of the conversion function declarator @p D with
3009/// type @p R. If there are any errors in the declarator, this routine
3010/// will emit diagnostics and return true. Otherwise, it will return
3011/// false. Either way, the type @p R will be updated to reflect a
3012/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003013void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003014 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003015 // C++ [class.conv.fct]p1:
3016 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003017 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003018 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003019 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003020 if (!D.isInvalidType())
3021 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3022 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3023 << SourceRange(D.getIdentifierLoc());
3024 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003025 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003026 }
John McCalla3f81372010-04-13 00:04:31 +00003027
3028 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3029
Chris Lattner6e475012009-04-25 08:35:12 +00003030 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003031 // Conversion functions don't have return types, but the parser will
3032 // happily parse something like:
3033 //
3034 // class X {
3035 // float operator bool();
3036 // };
3037 //
3038 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003039 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3040 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3041 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003042 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003043 }
3044
John McCalla3f81372010-04-13 00:04:31 +00003045 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3046
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003047 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003048 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003049 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3050
3051 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003052 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003053 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003054 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003055 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003056 D.setInvalidType();
3057 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003058
John McCalla3f81372010-04-13 00:04:31 +00003059 // Diagnose "&operator bool()" and other such nonsense. This
3060 // is actually a gcc extension which we don't support.
3061 if (Proto->getResultType() != ConvType) {
3062 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3063 << Proto->getResultType();
3064 D.setInvalidType();
3065 ConvType = Proto->getResultType();
3066 }
3067
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003068 // C++ [class.conv.fct]p4:
3069 // The conversion-type-id shall not represent a function type nor
3070 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003071 if (ConvType->isArrayType()) {
3072 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3073 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003074 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003075 } else if (ConvType->isFunctionType()) {
3076 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3077 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003078 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003079 }
3080
3081 // Rebuild the function type "R" without any parameters (in case any
3082 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003083 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003084 if (D.isInvalidType()) {
3085 R = Context.getFunctionType(ConvType, 0, 0, false,
3086 Proto->getTypeQuals(),
3087 Proto->hasExceptionSpec(),
3088 Proto->hasAnyExceptionSpec(),
3089 Proto->getNumExceptions(),
3090 Proto->exception_begin(),
3091 Proto->getExtInfo());
3092 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003093
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003094 // C++0x explicit conversion operators.
3095 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003096 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003097 diag::warn_explicit_conversion_functions)
3098 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003099}
3100
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003101/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3102/// the declaration of the given C++ conversion function. This routine
3103/// is responsible for recording the conversion function in the C++
3104/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003105Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003106 assert(Conversion && "Expected to receive a conversion function declaration");
3107
Douglas Gregor9d350972008-12-12 08:25:50 +00003108 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003109
3110 // Make sure we aren't redeclaring the conversion function.
3111 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003112
3113 // C++ [class.conv.fct]p1:
3114 // [...] A conversion function is never used to convert a
3115 // (possibly cv-qualified) object to the (possibly cv-qualified)
3116 // same object type (or a reference to it), to a (possibly
3117 // cv-qualified) base class of that type (or a reference to it),
3118 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003119 // FIXME: Suppress this warning if the conversion function ends up being a
3120 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003121 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003122 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003123 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003124 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003125 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3126 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003127 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003128 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003129 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3130 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003131 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003132 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003133 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003134 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003135 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003136 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003137 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003138 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003139 }
3140
Douglas Gregore80622f2010-09-29 04:25:11 +00003141 if (FunctionTemplateDecl *ConversionTemplate
3142 = Conversion->getDescribedFunctionTemplate())
3143 return ConversionTemplate;
3144
John McCalld226f652010-08-21 09:40:31 +00003145 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003146}
3147
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003148//===----------------------------------------------------------------------===//
3149// Namespace Handling
3150//===----------------------------------------------------------------------===//
3151
John McCallea318642010-08-26 09:15:37 +00003152
3153
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003154/// ActOnStartNamespaceDef - This is called at the start of a namespace
3155/// definition.
John McCalld226f652010-08-21 09:40:31 +00003156Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003157 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003158 SourceLocation IdentLoc,
3159 IdentifierInfo *II,
3160 SourceLocation LBrace,
3161 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003162 // anonymous namespace starts at its left brace
3163 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3164 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003165 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003166 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003167
3168 Scope *DeclRegionScope = NamespcScope->getParent();
3169
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003170 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3171
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003172 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallea318642010-08-26 09:15:37 +00003173 PushVisibilityAttr(attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003174
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003175 if (II) {
3176 // C++ [namespace.def]p2:
3177 // The identifier in an original-namespace-definition shall not have been
3178 // previously defined in the declarative region in which the
3179 // original-namespace-definition appears. The identifier in an
3180 // original-namespace-definition is the name of the namespace. Subsequently
3181 // in that declarative region, it is treated as an original-namespace-name.
3182
John McCallf36e02d2009-10-09 21:13:30 +00003183 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003184 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003185 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Douglas Gregor44b43212008-12-11 16:49:14 +00003187 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3188 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003189 if (Namespc->isInline() != OrigNS->isInline()) {
3190 // inline-ness must match
3191 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3192 << Namespc->isInline();
3193 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3194 Namespc->setInvalidDecl();
3195 // Recover by ignoring the new namespace's inline status.
3196 Namespc->setInline(OrigNS->isInline());
3197 }
3198
Douglas Gregor44b43212008-12-11 16:49:14 +00003199 // Attach this namespace decl to the chain of extended namespace
3200 // definitions.
3201 OrigNS->setNextNamespace(Namespc);
3202 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003203
Mike Stump1eb44332009-09-09 15:08:12 +00003204 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003205 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003206 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003207 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003208 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003209 } else if (PrevDecl) {
3210 // This is an invalid name redefinition.
3211 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3212 << Namespc->getDeclName();
3213 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3214 Namespc->setInvalidDecl();
3215 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003216 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003217 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003218 // This is the first "real" definition of the namespace "std", so update
3219 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003220 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003221 // We had already defined a dummy namespace "std". Link this new
3222 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003223 StdNS->setNextNamespace(Namespc);
3224 StdNS->setLocation(IdentLoc);
3225 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003226 }
3227
3228 // Make our StdNamespace cache point at the first real definition of the
3229 // "std" namespace.
3230 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003231 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003232
3233 PushOnScopeChains(Namespc, DeclRegionScope);
3234 } else {
John McCall9aeed322009-10-01 00:25:31 +00003235 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003236 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003237
3238 // Link the anonymous namespace into its parent.
3239 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003240 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003241 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3242 PrevDecl = TU->getAnonymousNamespace();
3243 TU->setAnonymousNamespace(Namespc);
3244 } else {
3245 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3246 PrevDecl = ND->getAnonymousNamespace();
3247 ND->setAnonymousNamespace(Namespc);
3248 }
3249
3250 // Link the anonymous namespace with its previous declaration.
3251 if (PrevDecl) {
3252 assert(PrevDecl->isAnonymousNamespace());
3253 assert(!PrevDecl->getNextNamespace());
3254 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3255 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003256
3257 if (Namespc->isInline() != PrevDecl->isInline()) {
3258 // inline-ness must match
3259 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3260 << Namespc->isInline();
3261 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3262 Namespc->setInvalidDecl();
3263 // Recover by ignoring the new namespace's inline status.
3264 Namespc->setInline(PrevDecl->isInline());
3265 }
John McCall5fdd7642009-12-16 02:06:49 +00003266 }
John McCall9aeed322009-10-01 00:25:31 +00003267
Douglas Gregora4181472010-03-24 00:46:35 +00003268 CurContext->addDecl(Namespc);
3269
John McCall9aeed322009-10-01 00:25:31 +00003270 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3271 // behaves as if it were replaced by
3272 // namespace unique { /* empty body */ }
3273 // using namespace unique;
3274 // namespace unique { namespace-body }
3275 // where all occurrences of 'unique' in a translation unit are
3276 // replaced by the same identifier and this identifier differs
3277 // from all other identifiers in the entire program.
3278
3279 // We just create the namespace with an empty name and then add an
3280 // implicit using declaration, just like the standard suggests.
3281 //
3282 // CodeGen enforces the "universally unique" aspect by giving all
3283 // declarations semantically contained within an anonymous
3284 // namespace internal linkage.
3285
John McCall5fdd7642009-12-16 02:06:49 +00003286 if (!PrevDecl) {
3287 UsingDirectiveDecl* UD
3288 = UsingDirectiveDecl::Create(Context, CurContext,
3289 /* 'using' */ LBrace,
3290 /* 'namespace' */ SourceLocation(),
3291 /* qualifier */ SourceRange(),
3292 /* NNS */ NULL,
3293 /* identifier */ SourceLocation(),
3294 Namespc,
3295 /* Ancestor */ CurContext);
3296 UD->setImplicit();
3297 CurContext->addDecl(UD);
3298 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003299 }
3300
3301 // Although we could have an invalid decl (i.e. the namespace name is a
3302 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003303 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3304 // for the namespace has the declarations that showed up in that particular
3305 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003306 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003307 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003308}
3309
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003310/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3311/// is a namespace alias, returns the namespace it points to.
3312static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3313 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3314 return AD->getNamespace();
3315 return dyn_cast_or_null<NamespaceDecl>(D);
3316}
3317
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003318/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3319/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003320void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003321 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3322 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3323 Namespc->setRBracLoc(RBrace);
3324 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003325 if (Namespc->hasAttr<VisibilityAttr>())
3326 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003327}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003328
John McCall384aff82010-08-25 07:42:41 +00003329CXXRecordDecl *Sema::getStdBadAlloc() const {
3330 return cast_or_null<CXXRecordDecl>(
3331 StdBadAlloc.get(Context.getExternalSource()));
3332}
3333
3334NamespaceDecl *Sema::getStdNamespace() const {
3335 return cast_or_null<NamespaceDecl>(
3336 StdNamespace.get(Context.getExternalSource()));
3337}
3338
Douglas Gregor66992202010-06-29 17:53:46 +00003339/// \brief Retrieve the special "std" namespace, which may require us to
3340/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003341NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003342 if (!StdNamespace) {
3343 // The "std" namespace has not yet been defined, so build one implicitly.
3344 StdNamespace = NamespaceDecl::Create(Context,
3345 Context.getTranslationUnitDecl(),
3346 SourceLocation(),
3347 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003348 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003349 }
3350
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003351 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003352}
3353
John McCalld226f652010-08-21 09:40:31 +00003354Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003355 SourceLocation UsingLoc,
3356 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003357 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003358 SourceLocation IdentLoc,
3359 IdentifierInfo *NamespcName,
3360 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003361 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3362 assert(NamespcName && "Invalid NamespcName.");
3363 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003364 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003365
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003366 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003367 NestedNameSpecifier *Qualifier = 0;
3368 if (SS.isSet())
3369 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3370
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003371 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003372 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3373 LookupParsedName(R, S, &SS);
3374 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003375 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003376
Douglas Gregor66992202010-06-29 17:53:46 +00003377 if (R.empty()) {
3378 // Allow "using namespace std;" or "using namespace ::std;" even if
3379 // "std" hasn't been defined yet, for GCC compatibility.
3380 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3381 NamespcName->isStr("std")) {
3382 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003383 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003384 R.resolveKind();
3385 }
3386 // Otherwise, attempt typo correction.
3387 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3388 CTC_NoKeywords, 0)) {
3389 if (R.getAsSingle<NamespaceDecl>() ||
3390 R.getAsSingle<NamespaceAliasDecl>()) {
3391 if (DeclContext *DC = computeDeclContext(SS, false))
3392 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3393 << NamespcName << DC << Corrected << SS.getRange()
3394 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3395 else
3396 Diag(IdentLoc, diag::err_using_directive_suggest)
3397 << NamespcName << Corrected
3398 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3399 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3400 << Corrected;
3401
3402 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003403 } else {
3404 R.clear();
3405 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003406 }
3407 }
3408 }
3409
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;
John McCalld226f652010-08-21 09:40:31 +00003442 return 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.
John McCalld226f652010-08-21 09:40:31 +00003454 S->PushUsingDirective(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
John McCalld226f652010-08-21 09:40:31 +00003458Decl *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();
John McCalld226f652010-08-21 09:40:31 +00003483 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003484
3485 case UnqualifiedId::IK_DestructorName:
3486 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3487 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003488 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003489
3490 case UnqualifiedId::IK_TemplateId:
3491 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3492 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003493 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003494 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003495
3496 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3497 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003498 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003499 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003500
John McCall60fa3cf2009-12-11 02:10:03 +00003501 // Warn about using declarations.
3502 // TODO: store that the declaration was written without 'using' and
3503 // talk about access decls instead of using decls in the
3504 // diagnostics.
3505 if (!HasUsingKeyword) {
3506 UsingLoc = Name.getSourceRange().getBegin();
3507
3508 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003509 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003510 }
3511
John McCall9488ea12009-11-17 05:59:44 +00003512 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003513 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003514 /* 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
John McCalld226f652010-08-21 09:40:31 +00003519 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003520}
3521
Douglas Gregor09acc982010-07-07 23:08:52 +00003522/// \brief Determine whether a using declaration considers the given
3523/// declarations as "equivalent", e.g., if they are redeclarations of
3524/// the same entity or are both typedefs of the same type.
3525static bool
3526IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3527 bool &SuppressRedeclaration) {
3528 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3529 SuppressRedeclaration = false;
3530 return true;
3531 }
3532
3533 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3534 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3535 SuppressRedeclaration = true;
3536 return Context.hasSameType(TD1->getUnderlyingType(),
3537 TD2->getUnderlyingType());
3538 }
3539
3540 return false;
3541}
3542
3543
John McCall9f54ad42009-12-10 09:41:52 +00003544/// Determines whether to create a using shadow decl for a particular
3545/// decl, given the set of decls existing prior to this using lookup.
3546bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3547 const LookupResult &Previous) {
3548 // Diagnose finding a decl which is not from a base class of the
3549 // current class. We do this now because there are cases where this
3550 // function will silently decide not to build a shadow decl, which
3551 // will pre-empt further diagnostics.
3552 //
3553 // We don't need to do this in C++0x because we do the check once on
3554 // the qualifier.
3555 //
3556 // FIXME: diagnose the following if we care enough:
3557 // struct A { int foo; };
3558 // struct B : A { using A::foo; };
3559 // template <class T> struct C : A {};
3560 // template <class T> struct D : C<T> { using B::foo; } // <---
3561 // This is invalid (during instantiation) in C++03 because B::foo
3562 // resolves to the using decl in B, which is not a base class of D<T>.
3563 // We can't diagnose it immediately because C<T> is an unknown
3564 // specialization. The UsingShadowDecl in D<T> then points directly
3565 // to A::foo, which will look well-formed when we instantiate.
3566 // The right solution is to not collapse the shadow-decl chain.
3567 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3568 DeclContext *OrigDC = Orig->getDeclContext();
3569
3570 // Handle enums and anonymous structs.
3571 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3572 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3573 while (OrigRec->isAnonymousStructOrUnion())
3574 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3575
3576 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3577 if (OrigDC == CurContext) {
3578 Diag(Using->getLocation(),
3579 diag::err_using_decl_nested_name_specifier_is_current_class)
3580 << Using->getNestedNameRange();
3581 Diag(Orig->getLocation(), diag::note_using_decl_target);
3582 return true;
3583 }
3584
3585 Diag(Using->getNestedNameRange().getBegin(),
3586 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3587 << Using->getTargetNestedNameDecl()
3588 << cast<CXXRecordDecl>(CurContext)
3589 << Using->getNestedNameRange();
3590 Diag(Orig->getLocation(), diag::note_using_decl_target);
3591 return true;
3592 }
3593 }
3594
3595 if (Previous.empty()) return false;
3596
3597 NamedDecl *Target = Orig;
3598 if (isa<UsingShadowDecl>(Target))
3599 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3600
John McCalld7533ec2009-12-11 02:33:26 +00003601 // If the target happens to be one of the previous declarations, we
3602 // don't have a conflict.
3603 //
3604 // FIXME: but we might be increasing its access, in which case we
3605 // should redeclare it.
3606 NamedDecl *NonTag = 0, *Tag = 0;
3607 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3608 I != E; ++I) {
3609 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003610 bool Result;
3611 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3612 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003613
3614 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3615 }
3616
John McCall9f54ad42009-12-10 09:41:52 +00003617 if (Target->isFunctionOrFunctionTemplate()) {
3618 FunctionDecl *FD;
3619 if (isa<FunctionTemplateDecl>(Target))
3620 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3621 else
3622 FD = cast<FunctionDecl>(Target);
3623
3624 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003625 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003626 case Ovl_Overload:
3627 return false;
3628
3629 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003630 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003631 break;
3632
3633 // We found a decl with the exact signature.
3634 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003635 // If we're in a record, we want to hide the target, so we
3636 // return true (without a diagnostic) to tell the caller not to
3637 // build a shadow decl.
3638 if (CurContext->isRecord())
3639 return true;
3640
3641 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003642 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003643 break;
3644 }
3645
3646 Diag(Target->getLocation(), diag::note_using_decl_target);
3647 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3648 return true;
3649 }
3650
3651 // Target is not a function.
3652
John McCall9f54ad42009-12-10 09:41:52 +00003653 if (isa<TagDecl>(Target)) {
3654 // No conflict between a tag and a non-tag.
3655 if (!Tag) return false;
3656
John McCall41ce66f2009-12-10 19:51:03 +00003657 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003658 Diag(Target->getLocation(), diag::note_using_decl_target);
3659 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3660 return true;
3661 }
3662
3663 // No conflict between a tag and a non-tag.
3664 if (!NonTag) return false;
3665
John McCall41ce66f2009-12-10 19:51:03 +00003666 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003667 Diag(Target->getLocation(), diag::note_using_decl_target);
3668 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3669 return true;
3670}
3671
John McCall9488ea12009-11-17 05:59:44 +00003672/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003673UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003674 UsingDecl *UD,
3675 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003676
3677 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003678 NamedDecl *Target = Orig;
3679 if (isa<UsingShadowDecl>(Target)) {
3680 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3681 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003682 }
3683
3684 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003685 = UsingShadowDecl::Create(Context, CurContext,
3686 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003687 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003688
3689 Shadow->setAccess(UD->getAccess());
3690 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3691 Shadow->setInvalidDecl();
3692
John McCall9488ea12009-11-17 05:59:44 +00003693 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003694 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003695 else
John McCall604e7f12009-12-08 07:46:18 +00003696 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003697
John McCall604e7f12009-12-08 07:46:18 +00003698
John McCall9f54ad42009-12-10 09:41:52 +00003699 return Shadow;
3700}
John McCall604e7f12009-12-08 07:46:18 +00003701
John McCall9f54ad42009-12-10 09:41:52 +00003702/// Hides a using shadow declaration. This is required by the current
3703/// using-decl implementation when a resolvable using declaration in a
3704/// class is followed by a declaration which would hide or override
3705/// one or more of the using decl's targets; for example:
3706///
3707/// struct Base { void foo(int); };
3708/// struct Derived : Base {
3709/// using Base::foo;
3710/// void foo(int);
3711/// };
3712///
3713/// The governing language is C++03 [namespace.udecl]p12:
3714///
3715/// When a using-declaration brings names from a base class into a
3716/// derived class scope, member functions in the derived class
3717/// override and/or hide member functions with the same name and
3718/// parameter types in a base class (rather than conflicting).
3719///
3720/// There are two ways to implement this:
3721/// (1) optimistically create shadow decls when they're not hidden
3722/// by existing declarations, or
3723/// (2) don't create any shadow decls (or at least don't make them
3724/// visible) until we've fully parsed/instantiated the class.
3725/// The problem with (1) is that we might have to retroactively remove
3726/// a shadow decl, which requires several O(n) operations because the
3727/// decl structures are (very reasonably) not designed for removal.
3728/// (2) avoids this but is very fiddly and phase-dependent.
3729void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003730 if (Shadow->getDeclName().getNameKind() ==
3731 DeclarationName::CXXConversionFunctionName)
3732 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3733
John McCall9f54ad42009-12-10 09:41:52 +00003734 // Remove it from the DeclContext...
3735 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003736
John McCall9f54ad42009-12-10 09:41:52 +00003737 // ...and the scope, if applicable...
3738 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003739 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003740 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003741 }
3742
John McCall9f54ad42009-12-10 09:41:52 +00003743 // ...and the using decl.
3744 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3745
3746 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003747 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003748}
3749
John McCall7ba107a2009-11-18 02:36:19 +00003750/// Builds a using declaration.
3751///
3752/// \param IsInstantiation - Whether this call arises from an
3753/// instantiation of an unresolved using declaration. We treat
3754/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003755NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3756 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003757 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003758 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003759 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003760 bool IsInstantiation,
3761 bool IsTypeName,
3762 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003763 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003764 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003765 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003766
Anders Carlsson550b14b2009-08-28 05:49:21 +00003767 // FIXME: We ignore attributes for now.
3768 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003770 if (SS.isEmpty()) {
3771 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003772 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003773 }
Mike Stump1eb44332009-09-09 15:08:12 +00003774
John McCall9f54ad42009-12-10 09:41:52 +00003775 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003776 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003777 ForRedeclaration);
3778 Previous.setHideTags(false);
3779 if (S) {
3780 LookupName(Previous, S);
3781
3782 // It is really dumb that we have to do this.
3783 LookupResult::Filter F = Previous.makeFilter();
3784 while (F.hasNext()) {
3785 NamedDecl *D = F.next();
3786 if (!isDeclInScope(D, CurContext, S))
3787 F.erase();
3788 }
3789 F.done();
3790 } else {
3791 assert(IsInstantiation && "no scope in non-instantiation");
3792 assert(CurContext->isRecord() && "scope not record in instantiation");
3793 LookupQualifiedName(Previous, CurContext);
3794 }
3795
Mike Stump1eb44332009-09-09 15:08:12 +00003796 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003797 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3798
John McCall9f54ad42009-12-10 09:41:52 +00003799 // Check for invalid redeclarations.
3800 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3801 return 0;
3802
3803 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003804 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3805 return 0;
3806
John McCallaf8e6ed2009-11-12 03:15:40 +00003807 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003808 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003809 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003810 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003811 // FIXME: not all declaration name kinds are legal here
3812 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3813 UsingLoc, TypenameLoc,
3814 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003815 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003816 } else {
3817 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003818 UsingLoc, SS.getRange(),
3819 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003820 }
John McCalled976492009-12-04 22:46:56 +00003821 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003822 D = UsingDecl::Create(Context, CurContext,
3823 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003824 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003825 }
John McCalled976492009-12-04 22:46:56 +00003826 D->setAccess(AS);
3827 CurContext->addDecl(D);
3828
3829 if (!LookupContext) return D;
3830 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003831
John McCall77bb1aa2010-05-01 00:40:08 +00003832 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003833 UD->setInvalidDecl();
3834 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003835 }
3836
John McCall604e7f12009-12-08 07:46:18 +00003837 // Look up the target name.
3838
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003839 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003840
John McCall604e7f12009-12-08 07:46:18 +00003841 // Unlike most lookups, we don't always want to hide tag
3842 // declarations: tag names are visible through the using declaration
3843 // even if hidden by ordinary names, *except* in a dependent context
3844 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003845 if (!IsInstantiation)
3846 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003847
John McCalla24dc2e2009-11-17 02:14:36 +00003848 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003849
John McCallf36e02d2009-10-09 21:13:30 +00003850 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003851 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003852 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003853 UD->setInvalidDecl();
3854 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003855 }
3856
John McCalled976492009-12-04 22:46:56 +00003857 if (R.isAmbiguous()) {
3858 UD->setInvalidDecl();
3859 return UD;
3860 }
Mike Stump1eb44332009-09-09 15:08:12 +00003861
John McCall7ba107a2009-11-18 02:36:19 +00003862 if (IsTypeName) {
3863 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003864 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003865 Diag(IdentLoc, diag::err_using_typename_non_type);
3866 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3867 Diag((*I)->getUnderlyingDecl()->getLocation(),
3868 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003869 UD->setInvalidDecl();
3870 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003871 }
3872 } else {
3873 // If we asked for a non-typename and we got a type, error out,
3874 // but only if this is an instantiation of an unresolved using
3875 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003876 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003877 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3878 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003879 UD->setInvalidDecl();
3880 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003881 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003882 }
3883
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003884 // C++0x N2914 [namespace.udecl]p6:
3885 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003886 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003887 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3888 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003889 UD->setInvalidDecl();
3890 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003891 }
Mike Stump1eb44332009-09-09 15:08:12 +00003892
John McCall9f54ad42009-12-10 09:41:52 +00003893 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3894 if (!CheckUsingShadowDecl(UD, *I, Previous))
3895 BuildUsingShadowDecl(S, UD, *I);
3896 }
John McCall9488ea12009-11-17 05:59:44 +00003897
3898 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003899}
3900
John McCall9f54ad42009-12-10 09:41:52 +00003901/// Checks that the given using declaration is not an invalid
3902/// redeclaration. Note that this is checking only for the using decl
3903/// itself, not for any ill-formedness among the UsingShadowDecls.
3904bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3905 bool isTypeName,
3906 const CXXScopeSpec &SS,
3907 SourceLocation NameLoc,
3908 const LookupResult &Prev) {
3909 // C++03 [namespace.udecl]p8:
3910 // C++0x [namespace.udecl]p10:
3911 // A using-declaration is a declaration and can therefore be used
3912 // repeatedly where (and only where) multiple declarations are
3913 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00003914 //
3915 // That's in non-member contexts.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003916 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00003917 return false;
3918
3919 NestedNameSpecifier *Qual
3920 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3921
3922 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3923 NamedDecl *D = *I;
3924
3925 bool DTypename;
3926 NestedNameSpecifier *DQual;
3927 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3928 DTypename = UD->isTypeName();
3929 DQual = UD->getTargetNestedNameDecl();
3930 } else if (UnresolvedUsingValueDecl *UD
3931 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3932 DTypename = false;
3933 DQual = UD->getTargetNestedNameSpecifier();
3934 } else if (UnresolvedUsingTypenameDecl *UD
3935 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3936 DTypename = true;
3937 DQual = UD->getTargetNestedNameSpecifier();
3938 } else continue;
3939
3940 // using decls differ if one says 'typename' and the other doesn't.
3941 // FIXME: non-dependent using decls?
3942 if (isTypeName != DTypename) continue;
3943
3944 // using decls differ if they name different scopes (but note that
3945 // template instantiation can cause this check to trigger when it
3946 // didn't before instantiation).
3947 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3948 Context.getCanonicalNestedNameSpecifier(DQual))
3949 continue;
3950
3951 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003952 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003953 return true;
3954 }
3955
3956 return false;
3957}
3958
John McCall604e7f12009-12-08 07:46:18 +00003959
John McCalled976492009-12-04 22:46:56 +00003960/// Checks that the given nested-name qualifier used in a using decl
3961/// in the current context is appropriately related to the current
3962/// scope. If an error is found, diagnoses it and returns true.
3963bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3964 const CXXScopeSpec &SS,
3965 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003966 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003967
John McCall604e7f12009-12-08 07:46:18 +00003968 if (!CurContext->isRecord()) {
3969 // C++03 [namespace.udecl]p3:
3970 // C++0x [namespace.udecl]p8:
3971 // A using-declaration for a class member shall be a member-declaration.
3972
3973 // If we weren't able to compute a valid scope, it must be a
3974 // dependent class scope.
3975 if (!NamedContext || NamedContext->isRecord()) {
3976 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3977 << SS.getRange();
3978 return true;
3979 }
3980
3981 // Otherwise, everything is known to be fine.
3982 return false;
3983 }
3984
3985 // The current scope is a record.
3986
3987 // If the named context is dependent, we can't decide much.
3988 if (!NamedContext) {
3989 // FIXME: in C++0x, we can diagnose if we can prove that the
3990 // nested-name-specifier does not refer to a base class, which is
3991 // still possible in some cases.
3992
3993 // Otherwise we have to conservatively report that things might be
3994 // okay.
3995 return false;
3996 }
3997
3998 if (!NamedContext->isRecord()) {
3999 // Ideally this would point at the last name in the specifier,
4000 // but we don't have that level of source info.
4001 Diag(SS.getRange().getBegin(),
4002 diag::err_using_decl_nested_name_specifier_is_not_class)
4003 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4004 return true;
4005 }
4006
4007 if (getLangOptions().CPlusPlus0x) {
4008 // C++0x [namespace.udecl]p3:
4009 // In a using-declaration used as a member-declaration, the
4010 // nested-name-specifier shall name a base class of the class
4011 // being defined.
4012
4013 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4014 cast<CXXRecordDecl>(NamedContext))) {
4015 if (CurContext == NamedContext) {
4016 Diag(NameLoc,
4017 diag::err_using_decl_nested_name_specifier_is_current_class)
4018 << SS.getRange();
4019 return true;
4020 }
4021
4022 Diag(SS.getRange().getBegin(),
4023 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4024 << (NestedNameSpecifier*) SS.getScopeRep()
4025 << cast<CXXRecordDecl>(CurContext)
4026 << SS.getRange();
4027 return true;
4028 }
4029
4030 return false;
4031 }
4032
4033 // C++03 [namespace.udecl]p4:
4034 // A using-declaration used as a member-declaration shall refer
4035 // to a member of a base class of the class being defined [etc.].
4036
4037 // Salient point: SS doesn't have to name a base class as long as
4038 // lookup only finds members from base classes. Therefore we can
4039 // diagnose here only if we can prove that that can't happen,
4040 // i.e. if the class hierarchies provably don't intersect.
4041
4042 // TODO: it would be nice if "definitely valid" results were cached
4043 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4044 // need to be repeated.
4045
4046 struct UserData {
4047 llvm::DenseSet<const CXXRecordDecl*> Bases;
4048
4049 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4050 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4051 Data->Bases.insert(Base);
4052 return true;
4053 }
4054
4055 bool hasDependentBases(const CXXRecordDecl *Class) {
4056 return !Class->forallBases(collect, this);
4057 }
4058
4059 /// Returns true if the base is dependent or is one of the
4060 /// accumulated base classes.
4061 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4062 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4063 return !Data->Bases.count(Base);
4064 }
4065
4066 bool mightShareBases(const CXXRecordDecl *Class) {
4067 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4068 }
4069 };
4070
4071 UserData Data;
4072
4073 // Returns false if we find a dependent base.
4074 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4075 return false;
4076
4077 // Returns false if the class has a dependent base or if it or one
4078 // of its bases is present in the base set of the current context.
4079 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4080 return false;
4081
4082 Diag(SS.getRange().getBegin(),
4083 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4084 << (NestedNameSpecifier*) SS.getScopeRep()
4085 << cast<CXXRecordDecl>(CurContext)
4086 << SS.getRange();
4087
4088 return true;
John McCalled976492009-12-04 22:46:56 +00004089}
4090
John McCalld226f652010-08-21 09:40:31 +00004091Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004092 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004093 SourceLocation AliasLoc,
4094 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004095 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004096 SourceLocation IdentLoc,
4097 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004098
Anders Carlsson81c85c42009-03-28 23:53:49 +00004099 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004100 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4101 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004102
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004103 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004104 NamedDecl *PrevDecl
4105 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4106 ForRedeclaration);
4107 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4108 PrevDecl = 0;
4109
4110 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004111 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004112 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004113 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004114 // FIXME: At some point, we'll want to create the (redundant)
4115 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004116 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004117 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004118 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004119 }
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004121 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4122 diag::err_redefinition_different_kind;
4123 Diag(AliasLoc, DiagID) << Alias;
4124 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004125 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004126 }
4127
John McCalla24dc2e2009-11-17 02:14:36 +00004128 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004129 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
John McCallf36e02d2009-10-09 21:13:30 +00004131 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004132 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4133 CTC_NoKeywords, 0)) {
4134 if (R.getAsSingle<NamespaceDecl>() ||
4135 R.getAsSingle<NamespaceAliasDecl>()) {
4136 if (DeclContext *DC = computeDeclContext(SS, false))
4137 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4138 << Ident << DC << Corrected << SS.getRange()
4139 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4140 else
4141 Diag(IdentLoc, diag::err_using_directive_suggest)
4142 << Ident << Corrected
4143 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4144
4145 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4146 << Corrected;
4147
4148 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004149 } else {
4150 R.clear();
4151 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004152 }
4153 }
4154
4155 if (R.empty()) {
4156 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004157 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004158 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004159 }
Mike Stump1eb44332009-09-09 15:08:12 +00004160
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004161 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004162 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4163 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004164 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004165 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004166
John McCall3dbd3d52010-02-16 06:53:13 +00004167 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004168 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004169}
4170
Douglas Gregor39957dc2010-05-01 15:04:51 +00004171namespace {
4172 /// \brief Scoped object used to handle the state changes required in Sema
4173 /// to implicitly define the body of a C++ member function;
4174 class ImplicitlyDefinedFunctionScope {
4175 Sema &S;
4176 DeclContext *PreviousContext;
4177
4178 public:
4179 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4180 : S(S), PreviousContext(S.CurContext)
4181 {
4182 S.CurContext = Method;
4183 S.PushFunctionScope();
4184 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4185 }
4186
4187 ~ImplicitlyDefinedFunctionScope() {
4188 S.PopExpressionEvaluationContext();
4189 S.PopFunctionOrBlockScope();
4190 S.CurContext = PreviousContext;
4191 }
4192 };
4193}
4194
Sebastian Redl751025d2010-09-13 22:02:47 +00004195static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4196 CXXRecordDecl *D) {
4197 ASTContext &Context = Self.Context;
4198 QualType ClassType = Context.getTypeDeclType(D);
4199 DeclarationName ConstructorName
4200 = Context.DeclarationNames.getCXXConstructorName(
4201 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4202
4203 DeclContext::lookup_const_iterator Con, ConEnd;
4204 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4205 Con != ConEnd; ++Con) {
4206 // FIXME: In C++0x, a constructor template can be a default constructor.
4207 if (isa<FunctionTemplateDecl>(*Con))
4208 continue;
4209
4210 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4211 if (Constructor->isDefaultConstructor())
4212 return Constructor;
4213 }
4214 return 0;
4215}
4216
Douglas Gregor23c94db2010-07-02 17:43:08 +00004217CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4218 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004219 // C++ [class.ctor]p5:
4220 // A default constructor for a class X is a constructor of class X
4221 // that can be called without an argument. If there is no
4222 // user-declared constructor for class X, a default constructor is
4223 // implicitly declared. An implicitly-declared default constructor
4224 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004225 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4226 "Should not build implicit default constructor!");
4227
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004228 // C++ [except.spec]p14:
4229 // An implicitly declared special member function (Clause 12) shall have an
4230 // exception-specification. [...]
4231 ImplicitExceptionSpecification ExceptSpec(Context);
4232
4233 // Direct base-class destructors.
4234 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4235 BEnd = ClassDecl->bases_end();
4236 B != BEnd; ++B) {
4237 if (B->isVirtual()) // Handled below.
4238 continue;
4239
Douglas Gregor18274032010-07-03 00:47:00 +00004240 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4241 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4242 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4243 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004244 else if (CXXConstructorDecl *Constructor
4245 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004246 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004247 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004248 }
4249
4250 // Virtual base-class destructors.
4251 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4252 BEnd = ClassDecl->vbases_end();
4253 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004254 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4255 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4256 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4257 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4258 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004259 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004260 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004261 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004262 }
4263
4264 // Field destructors.
4265 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4266 FEnd = ClassDecl->field_end();
4267 F != FEnd; ++F) {
4268 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004269 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4270 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4271 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4272 ExceptSpec.CalledDecl(
4273 DeclareImplicitDefaultConstructor(FieldClassDecl));
4274 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004275 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004276 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004277 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004278 }
4279
4280
4281 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004282 CanQualType ClassType
4283 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4284 DeclarationName Name
4285 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004286 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004287 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004288 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004289 Context.getFunctionType(Context.VoidTy,
4290 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004291 ExceptSpec.hasExceptionSpecification(),
4292 ExceptSpec.hasAnyExceptionSpecification(),
4293 ExceptSpec.size(),
4294 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004295 FunctionType::ExtInfo()),
4296 /*TInfo=*/0,
4297 /*isExplicit=*/false,
4298 /*isInline=*/true,
4299 /*isImplicitlyDeclared=*/true);
4300 DefaultCon->setAccess(AS_public);
4301 DefaultCon->setImplicit();
4302 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004303
4304 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004305 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4306
Douglas Gregor23c94db2010-07-02 17:43:08 +00004307 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004308 PushOnScopeChains(DefaultCon, S, false);
4309 ClassDecl->addDecl(DefaultCon);
4310
Douglas Gregor32df23e2010-07-01 22:02:46 +00004311 return DefaultCon;
4312}
4313
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004314void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4315 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004316 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004317 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004318 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004319
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004320 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004321 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004322
Douglas Gregor39957dc2010-05-01 15:04:51 +00004323 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004324 ErrorTrap Trap(*this);
4325 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4326 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004327 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004328 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004329 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004330 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004331 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004332
4333 SourceLocation Loc = Constructor->getLocation();
4334 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4335
4336 Constructor->setUsed();
4337 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004338}
4339
Douglas Gregor23c94db2010-07-02 17:43:08 +00004340CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004341 // C++ [class.dtor]p2:
4342 // If a class has no user-declared destructor, a destructor is
4343 // declared implicitly. An implicitly-declared destructor is an
4344 // inline public member of its class.
4345
4346 // C++ [except.spec]p14:
4347 // An implicitly declared special member function (Clause 12) shall have
4348 // an exception-specification.
4349 ImplicitExceptionSpecification ExceptSpec(Context);
4350
4351 // Direct base-class destructors.
4352 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4353 BEnd = ClassDecl->bases_end();
4354 B != BEnd; ++B) {
4355 if (B->isVirtual()) // Handled below.
4356 continue;
4357
4358 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4359 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004360 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004361 }
4362
4363 // Virtual base-class destructors.
4364 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4365 BEnd = ClassDecl->vbases_end();
4366 B != BEnd; ++B) {
4367 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4368 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004369 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004370 }
4371
4372 // Field destructors.
4373 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4374 FEnd = ClassDecl->field_end();
4375 F != FEnd; ++F) {
4376 if (const RecordType *RecordTy
4377 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4378 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004379 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004380 }
4381
Douglas Gregor4923aa22010-07-02 20:37:36 +00004382 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004383 QualType Ty = Context.getFunctionType(Context.VoidTy,
4384 0, 0, false, 0,
4385 ExceptSpec.hasExceptionSpecification(),
4386 ExceptSpec.hasAnyExceptionSpecification(),
4387 ExceptSpec.size(),
4388 ExceptSpec.data(),
4389 FunctionType::ExtInfo());
4390
4391 CanQualType ClassType
4392 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4393 DeclarationName Name
4394 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004395 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004396 CXXDestructorDecl *Destructor
Abramo Bagnara25777432010-08-11 22:01:17 +00004397 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004398 /*isInline=*/true,
4399 /*isImplicitlyDeclared=*/true);
4400 Destructor->setAccess(AS_public);
4401 Destructor->setImplicit();
4402 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004403
4404 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004405 ++ASTContext::NumImplicitDestructorsDeclared;
4406
4407 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004408 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004409 PushOnScopeChains(Destructor, S, false);
4410 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004411
4412 // This could be uniqued if it ever proves significant.
4413 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4414
4415 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004416
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004417 return Destructor;
4418}
4419
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004420void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004421 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004422 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004423 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004424 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004425 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004426
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004427 if (Destructor->isInvalidDecl())
4428 return;
4429
Douglas Gregor39957dc2010-05-01 15:04:51 +00004430 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004431
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004432 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004433 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4434 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004435
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004436 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004437 Diag(CurrentLocation, diag::note_member_synthesized_at)
4438 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4439
4440 Destructor->setInvalidDecl();
4441 return;
4442 }
4443
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004444 SourceLocation Loc = Destructor->getLocation();
4445 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4446
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004447 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004448 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004449}
4450
Douglas Gregor06a9f362010-05-01 20:49:11 +00004451/// \brief Builds a statement that copies the given entity from \p From to
4452/// \c To.
4453///
4454/// This routine is used to copy the members of a class with an
4455/// implicitly-declared copy assignment operator. When the entities being
4456/// copied are arrays, this routine builds for loops to copy them.
4457///
4458/// \param S The Sema object used for type-checking.
4459///
4460/// \param Loc The location where the implicit copy is being generated.
4461///
4462/// \param T The type of the expressions being copied. Both expressions must
4463/// have this type.
4464///
4465/// \param To The expression we are copying to.
4466///
4467/// \param From The expression we are copying from.
4468///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004469/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4470/// Otherwise, it's a non-static member subobject.
4471///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004472/// \param Depth Internal parameter recording the depth of the recursion.
4473///
4474/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004475static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004476BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004477 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004478 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004479 // C++0x [class.copy]p30:
4480 // Each subobject is assigned in the manner appropriate to its type:
4481 //
4482 // - if the subobject is of class type, the copy assignment operator
4483 // for the class is used (as if by explicit qualification; that is,
4484 // ignoring any possible virtual overriding functions in more derived
4485 // classes);
4486 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4487 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4488
4489 // Look for operator=.
4490 DeclarationName Name
4491 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4492 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4493 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4494
4495 // Filter out any result that isn't a copy-assignment operator.
4496 LookupResult::Filter F = OpLookup.makeFilter();
4497 while (F.hasNext()) {
4498 NamedDecl *D = F.next();
4499 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4500 if (Method->isCopyAssignmentOperator())
4501 continue;
4502
4503 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004504 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004505 F.done();
4506
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004507 // Suppress the protected check (C++ [class.protected]) for each of the
4508 // assignment operators we found. This strange dance is required when
4509 // we're assigning via a base classes's copy-assignment operator. To
4510 // ensure that we're getting the right base class subobject (without
4511 // ambiguities), we need to cast "this" to that subobject type; to
4512 // ensure that we don't go through the virtual call mechanism, we need
4513 // to qualify the operator= name with the base class (see below). However,
4514 // this means that if the base class has a protected copy assignment
4515 // operator, the protected member access check will fail. So, we
4516 // rewrite "protected" access to "public" access in this case, since we
4517 // know by construction that we're calling from a derived class.
4518 if (CopyingBaseSubobject) {
4519 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4520 L != LEnd; ++L) {
4521 if (L.getAccess() == AS_protected)
4522 L.setAccess(AS_public);
4523 }
4524 }
4525
Douglas Gregor06a9f362010-05-01 20:49:11 +00004526 // Create the nested-name-specifier that will be used to qualify the
4527 // reference to operator=; this is required to suppress the virtual
4528 // call mechanism.
4529 CXXScopeSpec SS;
4530 SS.setRange(Loc);
4531 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4532 T.getTypePtr()));
4533
4534 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004535 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004536 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004537 /*FirstQualifierInScope=*/0, OpLookup,
4538 /*TemplateArgs=*/0,
4539 /*SuppressQualifierCheck=*/true);
4540 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004541 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004542
4543 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004544
John McCall60d7b3a2010-08-24 06:29:42 +00004545 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004546 OpEqualRef.takeAs<Expr>(),
4547 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004548 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004549 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004550
4551 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004552 }
John McCallb0207482010-03-16 06:11:48 +00004553
Douglas Gregor06a9f362010-05-01 20:49:11 +00004554 // - if the subobject is of scalar type, the built-in assignment
4555 // operator is used.
4556 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4557 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004558 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004559 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004560 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004561
4562 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004563 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004564
4565 // - if the subobject is an array, each element is assigned, in the
4566 // manner appropriate to the element type;
4567
4568 // Construct a loop over the array bounds, e.g.,
4569 //
4570 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4571 //
4572 // that will copy each of the array elements.
4573 QualType SizeType = S.Context.getSizeType();
4574
4575 // Create the iteration variable.
4576 IdentifierInfo *IterationVarName = 0;
4577 {
4578 llvm::SmallString<8> Str;
4579 llvm::raw_svector_ostream OS(Str);
4580 OS << "__i" << Depth;
4581 IterationVarName = &S.Context.Idents.get(OS.str());
4582 }
4583 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4584 IterationVarName, SizeType,
4585 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004586 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004587
4588 // Initialize the iteration variable to zero.
4589 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004590 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004591
4592 // Create a reference to the iteration variable; we'll use this several
4593 // times throughout.
4594 Expr *IterationVarRef
4595 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4596 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4597
4598 // Create the DeclStmt that holds the iteration variable.
4599 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4600
4601 // Create the comparison against the array bound.
4602 llvm::APInt Upper = ArrayTy->getSize();
4603 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004604 Expr *Comparison
4605 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004606 IntegerLiteral::Create(S.Context,
4607 Upper, SizeType, Loc),
4608 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004609
4610 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004611 Expr *Increment
4612 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCall2de56d12010-08-25 11:45:40 +00004613 UO_PreInc,
John McCall9ae2f072010-08-23 23:25:46 +00004614 SizeType, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004615
4616 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004617 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4618 IterationVarRef, Loc));
4619 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4620 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004621
4622 // Build the copy for an individual element of the array.
John McCall60d7b3a2010-08-24 06:29:42 +00004623 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004624 ArrayTy->getElementType(),
John McCall9ae2f072010-08-23 23:25:46 +00004625 To, From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004626 CopyingBaseSubobject, Depth+1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004627 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004628 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004629
4630 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004631 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004632 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004633 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004634 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004635}
4636
Douglas Gregora376d102010-07-02 21:50:04 +00004637/// \brief Determine whether the given class has a copy assignment operator
4638/// that accepts a const-qualified argument.
4639static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4640 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4641
4642 if (!Class->hasDeclaredCopyAssignment())
4643 S.DeclareImplicitCopyAssignment(Class);
4644
4645 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4646 DeclarationName OpName
4647 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4648
4649 DeclContext::lookup_const_iterator Op, OpEnd;
4650 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4651 // C++ [class.copy]p9:
4652 // A user-declared copy assignment operator is a non-static non-template
4653 // member function of class X with exactly one parameter of type X, X&,
4654 // const X&, volatile X& or const volatile X&.
4655 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4656 if (!Method)
4657 continue;
4658
4659 if (Method->isStatic())
4660 continue;
4661 if (Method->getPrimaryTemplate())
4662 continue;
4663 const FunctionProtoType *FnType =
4664 Method->getType()->getAs<FunctionProtoType>();
4665 assert(FnType && "Overloaded operator has no prototype.");
4666 // Don't assert on this; an invalid decl might have been left in the AST.
4667 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4668 continue;
4669 bool AcceptsConst = true;
4670 QualType ArgType = FnType->getArgType(0);
4671 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4672 ArgType = Ref->getPointeeType();
4673 // Is it a non-const lvalue reference?
4674 if (!ArgType.isConstQualified())
4675 AcceptsConst = false;
4676 }
4677 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4678 continue;
4679
4680 // We have a single argument of type cv X or cv X&, i.e. we've found the
4681 // copy assignment operator. Return whether it accepts const arguments.
4682 return AcceptsConst;
4683 }
4684 assert(Class->isInvalidDecl() &&
4685 "No copy assignment operator declared in valid code.");
4686 return false;
4687}
4688
Douglas Gregor23c94db2010-07-02 17:43:08 +00004689CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004690 // Note: The following rules are largely analoguous to the copy
4691 // constructor rules. Note that virtual bases are not taken into account
4692 // for determining the argument type of the operator. Note also that
4693 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004694
4695
Douglas Gregord3c35902010-07-01 16:36:15 +00004696 // C++ [class.copy]p10:
4697 // If the class definition does not explicitly declare a copy
4698 // assignment operator, one is declared implicitly.
4699 // The implicitly-defined copy assignment operator for a class X
4700 // will have the form
4701 //
4702 // X& X::operator=(const X&)
4703 //
4704 // if
4705 bool HasConstCopyAssignment = true;
4706
4707 // -- each direct base class B of X has a copy assignment operator
4708 // whose parameter is of type const B&, const volatile B& or B,
4709 // and
4710 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4711 BaseEnd = ClassDecl->bases_end();
4712 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4713 assert(!Base->getType()->isDependentType() &&
4714 "Cannot generate implicit members for class with dependent bases.");
4715 const CXXRecordDecl *BaseClassDecl
4716 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004717 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004718 }
4719
4720 // -- for all the nonstatic data members of X that are of a class
4721 // type M (or array thereof), each such class type has a copy
4722 // assignment operator whose parameter is of type const M&,
4723 // const volatile M& or M.
4724 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4725 FieldEnd = ClassDecl->field_end();
4726 HasConstCopyAssignment && Field != FieldEnd;
4727 ++Field) {
4728 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4729 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4730 const CXXRecordDecl *FieldClassDecl
4731 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004732 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004733 }
4734 }
4735
4736 // Otherwise, the implicitly declared copy assignment operator will
4737 // have the form
4738 //
4739 // X& X::operator=(X&)
4740 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4741 QualType RetType = Context.getLValueReferenceType(ArgType);
4742 if (HasConstCopyAssignment)
4743 ArgType = ArgType.withConst();
4744 ArgType = Context.getLValueReferenceType(ArgType);
4745
Douglas Gregorb87786f2010-07-01 17:48:08 +00004746 // C++ [except.spec]p14:
4747 // An implicitly declared special member function (Clause 12) shall have an
4748 // exception-specification. [...]
4749 ImplicitExceptionSpecification ExceptSpec(Context);
4750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4751 BaseEnd = ClassDecl->bases_end();
4752 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004753 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004754 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004755
4756 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4757 DeclareImplicitCopyAssignment(BaseClassDecl);
4758
Douglas Gregorb87786f2010-07-01 17:48:08 +00004759 if (CXXMethodDecl *CopyAssign
4760 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4761 ExceptSpec.CalledDecl(CopyAssign);
4762 }
4763 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4764 FieldEnd = ClassDecl->field_end();
4765 Field != FieldEnd;
4766 ++Field) {
4767 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4768 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004769 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004770 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004771
4772 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4773 DeclareImplicitCopyAssignment(FieldClassDecl);
4774
Douglas Gregorb87786f2010-07-01 17:48:08 +00004775 if (CXXMethodDecl *CopyAssign
4776 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4777 ExceptSpec.CalledDecl(CopyAssign);
4778 }
4779 }
4780
Douglas Gregord3c35902010-07-01 16:36:15 +00004781 // An implicitly-declared copy assignment operator is an inline public
4782 // member of its class.
4783 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004784 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004785 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004786 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004787 Context.getFunctionType(RetType, &ArgType, 1,
4788 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004789 ExceptSpec.hasExceptionSpecification(),
4790 ExceptSpec.hasAnyExceptionSpecification(),
4791 ExceptSpec.size(),
4792 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004793 FunctionType::ExtInfo()),
4794 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004795 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004796 /*isInline=*/true);
4797 CopyAssignment->setAccess(AS_public);
4798 CopyAssignment->setImplicit();
4799 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004800
4801 // Add the parameter to the operator.
4802 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4803 ClassDecl->getLocation(),
4804 /*Id=*/0,
4805 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004806 SC_None,
4807 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004808 CopyAssignment->setParams(&FromParam, 1);
4809
Douglas Gregora376d102010-07-02 21:50:04 +00004810 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004811 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4812
Douglas Gregor23c94db2010-07-02 17:43:08 +00004813 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004814 PushOnScopeChains(CopyAssignment, S, false);
4815 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004816
4817 AddOverriddenMethods(ClassDecl, CopyAssignment);
4818 return CopyAssignment;
4819}
4820
Douglas Gregor06a9f362010-05-01 20:49:11 +00004821void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4822 CXXMethodDecl *CopyAssignOperator) {
4823 assert((CopyAssignOperator->isImplicit() &&
4824 CopyAssignOperator->isOverloadedOperator() &&
4825 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004826 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004827 "DefineImplicitCopyAssignment called for wrong function");
4828
4829 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4830
4831 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4832 CopyAssignOperator->setInvalidDecl();
4833 return;
4834 }
4835
4836 CopyAssignOperator->setUsed();
4837
4838 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004839 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004840
4841 // C++0x [class.copy]p30:
4842 // The implicitly-defined or explicitly-defaulted copy assignment operator
4843 // for a non-union class X performs memberwise copy assignment of its
4844 // subobjects. The direct base classes of X are assigned first, in the
4845 // order of their declaration in the base-specifier-list, and then the
4846 // immediate non-static data members of X are assigned, in the order in
4847 // which they were declared in the class definition.
4848
4849 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004850 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004851
4852 // The parameter for the "other" object, which we are copying from.
4853 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4854 Qualifiers OtherQuals = Other->getType().getQualifiers();
4855 QualType OtherRefType = Other->getType();
4856 if (const LValueReferenceType *OtherRef
4857 = OtherRefType->getAs<LValueReferenceType>()) {
4858 OtherRefType = OtherRef->getPointeeType();
4859 OtherQuals = OtherRefType.getQualifiers();
4860 }
4861
4862 // Our location for everything implicitly-generated.
4863 SourceLocation Loc = CopyAssignOperator->getLocation();
4864
4865 // Construct a reference to the "other" object. We'll be using this
4866 // throughout the generated ASTs.
4867 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4868 assert(OtherRef && "Reference to parameter cannot fail!");
4869
4870 // Construct the "this" pointer. We'll be using this throughout the generated
4871 // ASTs.
4872 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4873 assert(This && "Reference to this cannot fail!");
4874
4875 // Assign base classes.
4876 bool Invalid = false;
4877 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4878 E = ClassDecl->bases_end(); Base != E; ++Base) {
4879 // Form the assignment:
4880 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4881 QualType BaseType = Base->getType().getUnqualifiedType();
4882 CXXRecordDecl *BaseClassDecl = 0;
4883 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4884 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4885 else {
4886 Invalid = true;
4887 continue;
4888 }
4889
John McCallf871d0c2010-08-07 06:22:56 +00004890 CXXCastPath BasePath;
4891 BasePath.push_back(Base);
4892
Douglas Gregor06a9f362010-05-01 20:49:11 +00004893 // Construct the "from" expression, which is an implicit cast to the
4894 // appropriately-qualified base type.
4895 Expr *From = OtherRef->Retain();
4896 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004897 CK_UncheckedDerivedToBase,
4898 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004899
4900 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004901 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004902
4903 // Implicitly cast "this" to the appropriately-qualified base type.
4904 Expr *ToE = To.takeAs<Expr>();
4905 ImpCastExprToType(ToE,
4906 Context.getCVRQualifiedType(BaseType,
4907 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004908 CK_UncheckedDerivedToBase,
4909 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004910 To = Owned(ToE);
4911
4912 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004913 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004914 To.get(), From,
4915 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004916 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004917 Diag(CurrentLocation, diag::note_member_synthesized_at)
4918 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4919 CopyAssignOperator->setInvalidDecl();
4920 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004921 }
4922
4923 // Success! Record the copy.
4924 Statements.push_back(Copy.takeAs<Expr>());
4925 }
4926
4927 // \brief Reference to the __builtin_memcpy function.
4928 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00004929 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00004930 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004931
4932 // Assign non-static members.
4933 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4934 FieldEnd = ClassDecl->field_end();
4935 Field != FieldEnd; ++Field) {
4936 // Check for members of reference type; we can't copy those.
4937 if (Field->getType()->isReferenceType()) {
4938 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4939 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4940 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004941 Diag(CurrentLocation, diag::note_member_synthesized_at)
4942 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004943 Invalid = true;
4944 continue;
4945 }
4946
4947 // Check for members of const-qualified, non-class type.
4948 QualType BaseType = Context.getBaseElementType(Field->getType());
4949 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4950 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4951 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4952 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004953 Diag(CurrentLocation, diag::note_member_synthesized_at)
4954 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004955 Invalid = true;
4956 continue;
4957 }
4958
4959 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00004960 if (FieldType->isIncompleteArrayType()) {
4961 assert(ClassDecl->hasFlexibleArrayMember() &&
4962 "Incomplete array type is not valid");
4963 continue;
4964 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004965
4966 // Build references to the field in the object we're copying from and to.
4967 CXXScopeSpec SS; // Intentionally empty
4968 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4969 LookupMemberName);
4970 MemberLookup.addDecl(*Field);
4971 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00004972 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004973 Loc, /*IsArrow=*/false,
4974 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00004975 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00004976 Loc, /*IsArrow=*/true,
4977 SS, 0, MemberLookup, 0);
4978 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4979 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4980
4981 // If the field should be copied with __builtin_memcpy rather than via
4982 // explicit assignments, do so. This optimization only applies for arrays
4983 // of scalars and arrays of class type with trivial copy-assignment
4984 // operators.
4985 if (FieldType->isArrayType() &&
4986 (!BaseType->isRecordType() ||
4987 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4988 ->hasTrivialCopyAssignment())) {
4989 // Compute the size of the memory buffer to be copied.
4990 QualType SizeType = Context.getSizeType();
4991 llvm::APInt Size(Context.getTypeSize(SizeType),
4992 Context.getTypeSizeInChars(BaseType).getQuantity());
4993 for (const ConstantArrayType *Array
4994 = Context.getAsConstantArrayType(FieldType);
4995 Array;
4996 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4997 llvm::APInt ArraySize = Array->getSize();
4998 ArraySize.zextOrTrunc(Size.getBitWidth());
4999 Size *= ArraySize;
5000 }
5001
5002 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005003 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5004 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005005
5006 bool NeedsCollectableMemCpy =
5007 (BaseType->isRecordType() &&
5008 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5009
5010 if (NeedsCollectableMemCpy) {
5011 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005012 // Create a reference to the __builtin_objc_memmove_collectable function.
5013 LookupResult R(*this,
5014 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005015 Loc, LookupOrdinaryName);
5016 LookupName(R, TUScope, true);
5017
5018 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5019 if (!CollectableMemCpy) {
5020 // Something went horribly wrong earlier, and we will have
5021 // complained about it.
5022 Invalid = true;
5023 continue;
5024 }
5025
5026 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5027 CollectableMemCpy->getType(),
5028 Loc, 0).takeAs<Expr>();
5029 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5030 }
5031 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005032 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005033 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005034 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5035 LookupOrdinaryName);
5036 LookupName(R, TUScope, true);
5037
5038 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5039 if (!BuiltinMemCpy) {
5040 // Something went horribly wrong earlier, and we will have complained
5041 // about it.
5042 Invalid = true;
5043 continue;
5044 }
5045
5046 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5047 BuiltinMemCpy->getType(),
5048 Loc, 0).takeAs<Expr>();
5049 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5050 }
5051
John McCallca0408f2010-08-23 06:44:23 +00005052 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005053 CallArgs.push_back(To.takeAs<Expr>());
5054 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005055 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005056 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005057 if (NeedsCollectableMemCpy)
5058 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005059 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005060 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005061 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005062 else
5063 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005064 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005065 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005066 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005067
Douglas Gregor06a9f362010-05-01 20:49:11 +00005068 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5069 Statements.push_back(Call.takeAs<Expr>());
5070 continue;
5071 }
5072
5073 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005074 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005075 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005076 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005077 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005078 Diag(CurrentLocation, diag::note_member_synthesized_at)
5079 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5080 CopyAssignOperator->setInvalidDecl();
5081 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005082 }
5083
5084 // Success! Record the copy.
5085 Statements.push_back(Copy.takeAs<Stmt>());
5086 }
5087
5088 if (!Invalid) {
5089 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005090 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005091
John McCall60d7b3a2010-08-24 06:29:42 +00005092 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005093 if (Return.isInvalid())
5094 Invalid = true;
5095 else {
5096 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005097
5098 if (Trap.hasErrorOccurred()) {
5099 Diag(CurrentLocation, diag::note_member_synthesized_at)
5100 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5101 Invalid = true;
5102 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005103 }
5104 }
5105
5106 if (Invalid) {
5107 CopyAssignOperator->setInvalidDecl();
5108 return;
5109 }
5110
John McCall60d7b3a2010-08-24 06:29:42 +00005111 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005112 /*isStmtExpr=*/false);
5113 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5114 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005115}
5116
Douglas Gregor23c94db2010-07-02 17:43:08 +00005117CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5118 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005119 // C++ [class.copy]p4:
5120 // If the class definition does not explicitly declare a copy
5121 // constructor, one is declared implicitly.
5122
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005123 // C++ [class.copy]p5:
5124 // The implicitly-declared copy constructor for a class X will
5125 // have the form
5126 //
5127 // X::X(const X&)
5128 //
5129 // if
5130 bool HasConstCopyConstructor = true;
5131
5132 // -- each direct or virtual base class B of X has a copy
5133 // constructor whose first parameter is of type const B& or
5134 // const volatile B&, and
5135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5136 BaseEnd = ClassDecl->bases_end();
5137 HasConstCopyConstructor && Base != BaseEnd;
5138 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005139 // Virtual bases are handled below.
5140 if (Base->isVirtual())
5141 continue;
5142
Douglas Gregor22584312010-07-02 23:41:54 +00005143 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005144 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005145 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5146 DeclareImplicitCopyConstructor(BaseClassDecl);
5147
Douglas Gregor598a8542010-07-01 18:27:03 +00005148 HasConstCopyConstructor
5149 = BaseClassDecl->hasConstCopyConstructor(Context);
5150 }
5151
5152 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5153 BaseEnd = ClassDecl->vbases_end();
5154 HasConstCopyConstructor && Base != BaseEnd;
5155 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005156 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005157 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005158 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5159 DeclareImplicitCopyConstructor(BaseClassDecl);
5160
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005161 HasConstCopyConstructor
5162 = BaseClassDecl->hasConstCopyConstructor(Context);
5163 }
5164
5165 // -- for all the nonstatic data members of X that are of a
5166 // class type M (or array thereof), each such class type
5167 // has a copy constructor whose first parameter is of type
5168 // const M& or const volatile M&.
5169 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5170 FieldEnd = ClassDecl->field_end();
5171 HasConstCopyConstructor && Field != FieldEnd;
5172 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005173 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005174 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005175 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005176 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005177 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5178 DeclareImplicitCopyConstructor(FieldClassDecl);
5179
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005180 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005181 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005182 }
5183 }
5184
5185 // Otherwise, the implicitly declared copy constructor will have
5186 // the form
5187 //
5188 // X::X(X&)
5189 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5190 QualType ArgType = ClassType;
5191 if (HasConstCopyConstructor)
5192 ArgType = ArgType.withConst();
5193 ArgType = Context.getLValueReferenceType(ArgType);
5194
Douglas Gregor0d405db2010-07-01 20:59:04 +00005195 // C++ [except.spec]p14:
5196 // An implicitly declared special member function (Clause 12) shall have an
5197 // exception-specification. [...]
5198 ImplicitExceptionSpecification ExceptSpec(Context);
5199 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5200 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5201 BaseEnd = ClassDecl->bases_end();
5202 Base != BaseEnd;
5203 ++Base) {
5204 // Virtual bases are handled below.
5205 if (Base->isVirtual())
5206 continue;
5207
Douglas Gregor22584312010-07-02 23:41:54 +00005208 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005209 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005210 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5211 DeclareImplicitCopyConstructor(BaseClassDecl);
5212
Douglas Gregor0d405db2010-07-01 20:59:04 +00005213 if (CXXConstructorDecl *CopyConstructor
5214 = BaseClassDecl->getCopyConstructor(Context, Quals))
5215 ExceptSpec.CalledDecl(CopyConstructor);
5216 }
5217 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5218 BaseEnd = ClassDecl->vbases_end();
5219 Base != BaseEnd;
5220 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005221 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005223 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5224 DeclareImplicitCopyConstructor(BaseClassDecl);
5225
Douglas Gregor0d405db2010-07-01 20:59:04 +00005226 if (CXXConstructorDecl *CopyConstructor
5227 = BaseClassDecl->getCopyConstructor(Context, Quals))
5228 ExceptSpec.CalledDecl(CopyConstructor);
5229 }
5230 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5231 FieldEnd = ClassDecl->field_end();
5232 Field != FieldEnd;
5233 ++Field) {
5234 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5235 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005236 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005237 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005238 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5239 DeclareImplicitCopyConstructor(FieldClassDecl);
5240
Douglas Gregor0d405db2010-07-01 20:59:04 +00005241 if (CXXConstructorDecl *CopyConstructor
5242 = FieldClassDecl->getCopyConstructor(Context, Quals))
5243 ExceptSpec.CalledDecl(CopyConstructor);
5244 }
5245 }
5246
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005247 // An implicitly-declared copy constructor is an inline public
5248 // member of its class.
5249 DeclarationName Name
5250 = Context.DeclarationNames.getCXXConstructorName(
5251 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005252 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005253 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005254 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005255 Context.getFunctionType(Context.VoidTy,
5256 &ArgType, 1,
5257 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005258 ExceptSpec.hasExceptionSpecification(),
5259 ExceptSpec.hasAnyExceptionSpecification(),
5260 ExceptSpec.size(),
5261 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005262 FunctionType::ExtInfo()),
5263 /*TInfo=*/0,
5264 /*isExplicit=*/false,
5265 /*isInline=*/true,
5266 /*isImplicitlyDeclared=*/true);
5267 CopyConstructor->setAccess(AS_public);
5268 CopyConstructor->setImplicit();
5269 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5270
Douglas Gregor22584312010-07-02 23:41:54 +00005271 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005272 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5273
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005274 // Add the parameter to the constructor.
5275 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5276 ClassDecl->getLocation(),
5277 /*IdentifierInfo=*/0,
5278 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005279 SC_None,
5280 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005281 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005282 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005283 PushOnScopeChains(CopyConstructor, S, false);
5284 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005285
5286 return CopyConstructor;
5287}
5288
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005289void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5290 CXXConstructorDecl *CopyConstructor,
5291 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005292 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005293 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005294 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005295 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005296
Anders Carlsson63010a72010-04-23 16:24:12 +00005297 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005298 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005299
Douglas Gregor39957dc2010-05-01 15:04:51 +00005300 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005301 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005302
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005303 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5304 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005305 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005306 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005307 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005308 } else {
5309 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5310 CopyConstructor->getLocation(),
5311 MultiStmtArg(*this, 0, 0),
5312 /*isStmtExpr=*/false)
5313 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005314 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005315
5316 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005317}
5318
John McCall60d7b3a2010-08-24 06:29:42 +00005319ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005320Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005321 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005322 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005323 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005324 unsigned ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005325 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005326
Douglas Gregor2f599792010-04-02 18:24:57 +00005327 // C++0x [class.copy]p34:
5328 // When certain criteria are met, an implementation is allowed to
5329 // omit the copy/move construction of a class object, even if the
5330 // copy/move constructor and/or destructor for the object have
5331 // side effects. [...]
5332 // - when a temporary class object that has not been bound to a
5333 // reference (12.2) would be copied/moved to a class object
5334 // with the same cv-unqualified type, the copy/move operation
5335 // can be omitted by constructing the temporary object
5336 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005337 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5338 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005339 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005340 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005341 }
Mike Stump1eb44332009-09-09 15:08:12 +00005342
5343 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005344 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005345 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005346}
5347
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005348/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5349/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005350ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005351Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5352 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005353 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005354 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005355 unsigned ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005356 unsigned NumExprs = ExprArgs.size();
5357 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005358
Douglas Gregor7edfb692009-11-23 12:27:39 +00005359 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005360 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005361 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005362 RequiresZeroInit,
5363 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005364}
5365
Mike Stump1eb44332009-09-09 15:08:12 +00005366bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005367 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005368 MultiExprArg Exprs) {
John McCall60d7b3a2010-08-24 06:29:42 +00005369 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005370 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005371 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonfe2de492009-08-25 05:18:00 +00005372 if (TempResult.isInvalid())
5373 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005375 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005376 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005377 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00005378 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005379 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Anders Carlssonfe2de492009-08-25 05:18:00 +00005381 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005382}
5383
John McCall68c6c9a2010-02-02 09:10:11 +00005384void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5385 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005386 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005387 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005388 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005389 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005390 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005391 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005392 << VD->getDeclName()
5393 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005394
John McCallae792222010-09-18 05:25:11 +00005395 // TODO: this should be re-enabled for static locals by !CXAAtExit
5396 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005397 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005398 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005399}
5400
Mike Stump1eb44332009-09-09 15:08:12 +00005401/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005402/// ActOnDeclarator, when a C++ direct initializer is present.
5403/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005404void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005405 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005406 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005407 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005408 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005409
5410 // If there is no declaration, there was an error parsing it. Just ignore
5411 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005412 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005413 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005414
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005415 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5416 if (!VDecl) {
5417 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5418 RealDecl->setInvalidDecl();
5419 return;
5420 }
5421
Douglas Gregor83ddad32009-08-26 21:14:46 +00005422 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005423 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005424 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5425 //
5426 // Clients that want to distinguish between the two forms, can check for
5427 // direct initializer using VarDecl::hasCXXDirectInitializer().
5428 // A major benefit is that clients that don't particularly care about which
5429 // exactly form was it (like the CodeGen) can handle both cases without
5430 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005431
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005432 // C++ 8.5p11:
5433 // The form of initialization (using parentheses or '=') is generally
5434 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005435 // class type.
5436
Douglas Gregor4dffad62010-02-11 22:55:30 +00005437 if (!VDecl->getType()->isDependentType() &&
5438 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005439 diag::err_typecheck_decl_incomplete_type)) {
5440 VDecl->setInvalidDecl();
5441 return;
5442 }
5443
Douglas Gregor90f93822009-12-22 22:17:25 +00005444 // The variable can not have an abstract class type.
5445 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5446 diag::err_abstract_type_in_decl,
5447 AbstractVariableType))
5448 VDecl->setInvalidDecl();
5449
Sebastian Redl31310a22010-02-01 20:16:42 +00005450 const VarDecl *Def;
5451 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005452 Diag(VDecl->getLocation(), diag::err_redefinition)
5453 << VDecl->getDeclName();
5454 Diag(Def->getLocation(), diag::note_previous_definition);
5455 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005456 return;
5457 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005458
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005459 // C++ [class.static.data]p4
5460 // If a static data member is of const integral or const
5461 // enumeration type, its declaration in the class definition can
5462 // specify a constant-initializer which shall be an integral
5463 // constant expression (5.19). In that case, the member can appear
5464 // in integral constant expressions. The member shall still be
5465 // defined in a namespace scope if it is used in the program and the
5466 // namespace scope definition shall not contain an initializer.
5467 //
5468 // We already performed a redefinition check above, but for static
5469 // data members we also need to check whether there was an in-class
5470 // declaration with an initializer.
5471 const VarDecl* PrevInit = 0;
5472 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5473 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5474 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5475 return;
5476 }
5477
Douglas Gregor4dffad62010-02-11 22:55:30 +00005478 // If either the declaration has a dependent type or if any of the
5479 // expressions is type-dependent, we represent the initialization
5480 // via a ParenListExpr for later use during template instantiation.
5481 if (VDecl->getType()->isDependentType() ||
5482 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5483 // Let clients know that initialization was done with a direct initializer.
5484 VDecl->setCXXDirectInitializer(true);
5485
5486 // Store the initialization expressions as a ParenListExpr.
5487 unsigned NumExprs = Exprs.size();
5488 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5489 (Expr **)Exprs.release(),
5490 NumExprs, RParenLoc));
5491 return;
5492 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005493
5494 // Capture the variable that is being initialized and the style of
5495 // initialization.
5496 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5497
5498 // FIXME: Poor source location information.
5499 InitializationKind Kind
5500 = InitializationKind::CreateDirect(VDecl->getLocation(),
5501 LParenLoc, RParenLoc);
5502
5503 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005504 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005505 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005506 if (Result.isInvalid()) {
5507 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005508 return;
5509 }
John McCallb4eb64d2010-10-08 02:01:28 +00005510
5511 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005512
John McCall9ae2f072010-08-23 23:25:46 +00005513 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregor838db382010-02-11 01:19:42 +00005514 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005515 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005516
John McCall4204f072010-08-02 21:13:48 +00005517 if (!VDecl->isInvalidDecl() &&
5518 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005519 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005520 !VDecl->getInit()->isConstantInitializer(Context,
5521 VDecl->getType()->isReferenceType()))
5522 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5523 << VDecl->getInit()->getSourceRange();
5524
John McCall68c6c9a2010-02-02 09:10:11 +00005525 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5526 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005527}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005528
Douglas Gregor39da0b82009-09-09 23:08:42 +00005529/// \brief Given a constructor and the set of arguments provided for the
5530/// constructor, convert the arguments and add any required default arguments
5531/// to form a proper call to this constructor.
5532///
5533/// \returns true if an error occurred, false otherwise.
5534bool
5535Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5536 MultiExprArg ArgsPtr,
5537 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005538 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005539 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5540 unsigned NumArgs = ArgsPtr.size();
5541 Expr **Args = (Expr **)ArgsPtr.get();
5542
5543 const FunctionProtoType *Proto
5544 = Constructor->getType()->getAs<FunctionProtoType>();
5545 assert(Proto && "Constructor without a prototype?");
5546 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005547
5548 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005549 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005550 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005551 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005552 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005553
5554 VariadicCallType CallType =
5555 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5556 llvm::SmallVector<Expr *, 8> AllArgs;
5557 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5558 Proto, 0, Args, NumArgs, AllArgs,
5559 CallType);
5560 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5561 ConvertedArgs.push_back(AllArgs[i]);
5562 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005563}
5564
Anders Carlsson20d45d22009-12-12 00:32:00 +00005565static inline bool
5566CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5567 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005568 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005569 if (isa<NamespaceDecl>(DC)) {
5570 return SemaRef.Diag(FnDecl->getLocation(),
5571 diag::err_operator_new_delete_declared_in_namespace)
5572 << FnDecl->getDeclName();
5573 }
5574
5575 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005576 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005577 return SemaRef.Diag(FnDecl->getLocation(),
5578 diag::err_operator_new_delete_declared_static)
5579 << FnDecl->getDeclName();
5580 }
5581
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005582 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005583}
5584
Anders Carlsson156c78e2009-12-13 17:53:43 +00005585static inline bool
5586CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5587 CanQualType ExpectedResultType,
5588 CanQualType ExpectedFirstParamType,
5589 unsigned DependentParamTypeDiag,
5590 unsigned InvalidParamTypeDiag) {
5591 QualType ResultType =
5592 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5593
5594 // Check that the result type is not dependent.
5595 if (ResultType->isDependentType())
5596 return SemaRef.Diag(FnDecl->getLocation(),
5597 diag::err_operator_new_delete_dependent_result_type)
5598 << FnDecl->getDeclName() << ExpectedResultType;
5599
5600 // Check that the result type is what we expect.
5601 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5602 return SemaRef.Diag(FnDecl->getLocation(),
5603 diag::err_operator_new_delete_invalid_result_type)
5604 << FnDecl->getDeclName() << ExpectedResultType;
5605
5606 // A function template must have at least 2 parameters.
5607 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5608 return SemaRef.Diag(FnDecl->getLocation(),
5609 diag::err_operator_new_delete_template_too_few_parameters)
5610 << FnDecl->getDeclName();
5611
5612 // The function decl must have at least 1 parameter.
5613 if (FnDecl->getNumParams() == 0)
5614 return SemaRef.Diag(FnDecl->getLocation(),
5615 diag::err_operator_new_delete_too_few_parameters)
5616 << FnDecl->getDeclName();
5617
5618 // Check the the first parameter type is not dependent.
5619 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5620 if (FirstParamType->isDependentType())
5621 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5622 << FnDecl->getDeclName() << ExpectedFirstParamType;
5623
5624 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005625 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005626 ExpectedFirstParamType)
5627 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5628 << FnDecl->getDeclName() << ExpectedFirstParamType;
5629
5630 return false;
5631}
5632
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005633static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005634CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005635 // C++ [basic.stc.dynamic.allocation]p1:
5636 // A program is ill-formed if an allocation function is declared in a
5637 // namespace scope other than global scope or declared static in global
5638 // scope.
5639 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5640 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005641
5642 CanQualType SizeTy =
5643 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5644
5645 // C++ [basic.stc.dynamic.allocation]p1:
5646 // The return type shall be void*. The first parameter shall have type
5647 // std::size_t.
5648 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5649 SizeTy,
5650 diag::err_operator_new_dependent_param_type,
5651 diag::err_operator_new_param_type))
5652 return true;
5653
5654 // C++ [basic.stc.dynamic.allocation]p1:
5655 // The first parameter shall not have an associated default argument.
5656 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005657 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005658 diag::err_operator_new_default_arg)
5659 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5660
5661 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005662}
5663
5664static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005665CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5666 // C++ [basic.stc.dynamic.deallocation]p1:
5667 // A program is ill-formed if deallocation functions are declared in a
5668 // namespace scope other than global scope or declared static in global
5669 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005670 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5671 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005672
5673 // C++ [basic.stc.dynamic.deallocation]p2:
5674 // Each deallocation function shall return void and its first parameter
5675 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005676 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5677 SemaRef.Context.VoidPtrTy,
5678 diag::err_operator_delete_dependent_param_type,
5679 diag::err_operator_delete_param_type))
5680 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005681
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005682 return false;
5683}
5684
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005685/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5686/// of this overloaded operator is well-formed. If so, returns false;
5687/// otherwise, emits appropriate diagnostics and returns true.
5688bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005689 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005690 "Expected an overloaded operator declaration");
5691
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005692 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5693
Mike Stump1eb44332009-09-09 15:08:12 +00005694 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005695 // The allocation and deallocation functions, operator new,
5696 // operator new[], operator delete and operator delete[], are
5697 // described completely in 3.7.3. The attributes and restrictions
5698 // found in the rest of this subclause do not apply to them unless
5699 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005700 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005701 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005702
Anders Carlssona3ccda52009-12-12 00:26:23 +00005703 if (Op == OO_New || Op == OO_Array_New)
5704 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005705
5706 // C++ [over.oper]p6:
5707 // An operator function shall either be a non-static member
5708 // function or be a non-member function and have at least one
5709 // parameter whose type is a class, a reference to a class, an
5710 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005711 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5712 if (MethodDecl->isStatic())
5713 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005714 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005715 } else {
5716 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005717 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5718 ParamEnd = FnDecl->param_end();
5719 Param != ParamEnd; ++Param) {
5720 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005721 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5722 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005723 ClassOrEnumParam = true;
5724 break;
5725 }
5726 }
5727
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005728 if (!ClassOrEnumParam)
5729 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005730 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005731 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005732 }
5733
5734 // C++ [over.oper]p8:
5735 // An operator function cannot have default arguments (8.3.6),
5736 // except where explicitly stated below.
5737 //
Mike Stump1eb44332009-09-09 15:08:12 +00005738 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005739 // (C++ [over.call]p1).
5740 if (Op != OO_Call) {
5741 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5742 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005743 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005744 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005745 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005746 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005747 }
5748 }
5749
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005750 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5751 { false, false, false }
5752#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5753 , { Unary, Binary, MemberOnly }
5754#include "clang/Basic/OperatorKinds.def"
5755 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005756
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005757 bool CanBeUnaryOperator = OperatorUses[Op][0];
5758 bool CanBeBinaryOperator = OperatorUses[Op][1];
5759 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005760
5761 // C++ [over.oper]p8:
5762 // [...] Operator functions cannot have more or fewer parameters
5763 // than the number required for the corresponding operator, as
5764 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005765 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005766 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005767 if (Op != OO_Call &&
5768 ((NumParams == 1 && !CanBeUnaryOperator) ||
5769 (NumParams == 2 && !CanBeBinaryOperator) ||
5770 (NumParams < 1) || (NumParams > 2))) {
5771 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005772 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005773 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005774 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005775 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005776 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005777 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005778 assert(CanBeBinaryOperator &&
5779 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005780 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005781 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005782
Chris Lattner416e46f2008-11-21 07:57:12 +00005783 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005784 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005785 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005786
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005787 // Overloaded operators other than operator() cannot be variadic.
5788 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005789 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005790 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005791 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005792 }
5793
5794 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005795 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5796 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005797 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005798 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005799 }
5800
5801 // C++ [over.inc]p1:
5802 // The user-defined function called operator++ implements the
5803 // prefix and postfix ++ operator. If this function is a member
5804 // function with no parameters, or a non-member function with one
5805 // parameter of class or enumeration type, it defines the prefix
5806 // increment operator ++ for objects of that type. If the function
5807 // is a member function with one parameter (which shall be of type
5808 // int) or a non-member function with two parameters (the second
5809 // of which shall be of type int), it defines the postfix
5810 // increment operator ++ for objects of that type.
5811 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5812 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5813 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005814 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005815 ParamIsInt = BT->getKind() == BuiltinType::Int;
5816
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005817 if (!ParamIsInt)
5818 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005819 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005820 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005821 }
5822
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005823 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005824}
Chris Lattner5a003a42008-12-17 07:09:26 +00005825
Sean Hunta6c058d2010-01-13 09:01:02 +00005826/// CheckLiteralOperatorDeclaration - Check whether the declaration
5827/// of this literal operator function is well-formed. If so, returns
5828/// false; otherwise, emits appropriate diagnostics and returns true.
5829bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5830 DeclContext *DC = FnDecl->getDeclContext();
5831 Decl::Kind Kind = DC->getDeclKind();
5832 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5833 Kind != Decl::LinkageSpec) {
5834 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5835 << FnDecl->getDeclName();
5836 return true;
5837 }
5838
5839 bool Valid = false;
5840
Sean Hunt216c2782010-04-07 23:11:06 +00005841 // template <char...> type operator "" name() is the only valid template
5842 // signature, and the only valid signature with no parameters.
5843 if (FnDecl->param_size() == 0) {
5844 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5845 // Must have only one template parameter
5846 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5847 if (Params->size() == 1) {
5848 NonTypeTemplateParmDecl *PmDecl =
5849 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005850
Sean Hunt216c2782010-04-07 23:11:06 +00005851 // The template parameter must be a char parameter pack.
5852 // FIXME: This test will always fail because non-type parameter packs
5853 // have not been implemented.
5854 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5855 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5856 Valid = true;
5857 }
5858 }
5859 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005860 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005861 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5862
Sean Hunta6c058d2010-01-13 09:01:02 +00005863 QualType T = (*Param)->getType();
5864
Sean Hunt30019c02010-04-07 22:57:35 +00005865 // unsigned long long int, long double, and any character type are allowed
5866 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005867 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5868 Context.hasSameType(T, Context.LongDoubleTy) ||
5869 Context.hasSameType(T, Context.CharTy) ||
5870 Context.hasSameType(T, Context.WCharTy) ||
5871 Context.hasSameType(T, Context.Char16Ty) ||
5872 Context.hasSameType(T, Context.Char32Ty)) {
5873 if (++Param == FnDecl->param_end())
5874 Valid = true;
5875 goto FinishedParams;
5876 }
5877
Sean Hunt30019c02010-04-07 22:57:35 +00005878 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005879 const PointerType *PT = T->getAs<PointerType>();
5880 if (!PT)
5881 goto FinishedParams;
5882 T = PT->getPointeeType();
5883 if (!T.isConstQualified())
5884 goto FinishedParams;
5885 T = T.getUnqualifiedType();
5886
5887 // Move on to the second parameter;
5888 ++Param;
5889
5890 // If there is no second parameter, the first must be a const char *
5891 if (Param == FnDecl->param_end()) {
5892 if (Context.hasSameType(T, Context.CharTy))
5893 Valid = true;
5894 goto FinishedParams;
5895 }
5896
5897 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5898 // are allowed as the first parameter to a two-parameter function
5899 if (!(Context.hasSameType(T, Context.CharTy) ||
5900 Context.hasSameType(T, Context.WCharTy) ||
5901 Context.hasSameType(T, Context.Char16Ty) ||
5902 Context.hasSameType(T, Context.Char32Ty)))
5903 goto FinishedParams;
5904
5905 // The second and final parameter must be an std::size_t
5906 T = (*Param)->getType().getUnqualifiedType();
5907 if (Context.hasSameType(T, Context.getSizeType()) &&
5908 ++Param == FnDecl->param_end())
5909 Valid = true;
5910 }
5911
5912 // FIXME: This diagnostic is absolutely terrible.
5913FinishedParams:
5914 if (!Valid) {
5915 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5916 << FnDecl->getDeclName();
5917 return true;
5918 }
5919
5920 return false;
5921}
5922
Douglas Gregor074149e2009-01-05 19:45:36 +00005923/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5924/// linkage specification, including the language and (if present)
5925/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5926/// the location of the language string literal, which is provided
5927/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5928/// the '{' brace. Otherwise, this linkage specification does not
5929/// have any braces.
John McCalld226f652010-08-21 09:40:31 +00005930Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005931 SourceLocation ExternLoc,
5932 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00005933 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005934 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005935 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005936 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005937 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005938 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005939 Language = LinkageSpecDecl::lang_cxx;
5940 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005941 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00005942 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005943 }
Mike Stump1eb44332009-09-09 15:08:12 +00005944
Chris Lattnercc98eac2008-12-17 07:13:27 +00005945 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005946
Douglas Gregor074149e2009-01-05 19:45:36 +00005947 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005948 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005949 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005950 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005951 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00005952 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005953}
5954
Abramo Bagnara35f9a192010-07-30 16:47:02 +00005955/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00005956/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5957/// valid, it's the position of the closing '}' brace in a linkage
5958/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00005959Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
5960 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005961 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005962 if (LinkageSpec)
5963 PopDeclContext();
5964 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005965}
5966
Douglas Gregord308e622009-05-18 20:51:54 +00005967/// \brief Perform semantic analysis for the variable declaration that
5968/// occurs within a C++ catch clause, returning the newly-created
5969/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00005970VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00005971 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005972 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00005973 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00005974 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00005975 QualType ExDeclType = TInfo->getType();
5976
Sebastian Redl4b07b292008-12-22 19:15:10 +00005977 // Arrays and functions decay.
5978 if (ExDeclType->isArrayType())
5979 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5980 else if (ExDeclType->isFunctionType())
5981 ExDeclType = Context.getPointerType(ExDeclType);
5982
5983 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5984 // The exception-declaration shall not denote a pointer or reference to an
5985 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005986 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005987 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00005988 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005989 Invalid = true;
5990 }
Douglas Gregord308e622009-05-18 20:51:54 +00005991
Douglas Gregora2762912010-03-08 01:47:36 +00005992 // GCC allows catching pointers and references to incomplete types
5993 // as an extension; so do we, but we warn by default.
5994
Sebastian Redl4b07b292008-12-22 19:15:10 +00005995 QualType BaseType = ExDeclType;
5996 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005997 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00005998 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00005999 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006000 BaseType = Ptr->getPointeeType();
6001 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006002 DK = diag::ext_catch_incomplete_ptr;
6003 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006004 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006005 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006006 BaseType = Ref->getPointeeType();
6007 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006008 DK = diag::ext_catch_incomplete_ref;
6009 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006010 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006011 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006012 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6013 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006014 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006015
Mike Stump1eb44332009-09-09 15:08:12 +00006016 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006017 RequireNonAbstractType(Loc, ExDeclType,
6018 diag::err_abstract_type_in_decl,
6019 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006020 Invalid = true;
6021
John McCall5a180392010-07-24 00:37:23 +00006022 // Only the non-fragile NeXT runtime currently supports C++ catches
6023 // of ObjC types, and no runtime supports catching ObjC types by value.
6024 if (!Invalid && getLangOptions().ObjC1) {
6025 QualType T = ExDeclType;
6026 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6027 T = RT->getPointeeType();
6028
6029 if (T->isObjCObjectType()) {
6030 Diag(Loc, diag::err_objc_object_catch);
6031 Invalid = true;
6032 } else if (T->isObjCObjectPointerType()) {
6033 if (!getLangOptions().NeXTRuntime) {
6034 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6035 Invalid = true;
6036 } else if (!getLangOptions().ObjCNonFragileABI) {
6037 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6038 Invalid = true;
6039 }
6040 }
6041 }
6042
Mike Stump1eb44332009-09-09 15:08:12 +00006043 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006044 Name, ExDeclType, TInfo, SC_None,
6045 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006046 ExDecl->setExceptionVariable(true);
6047
Douglas Gregor6d182892010-03-05 23:38:39 +00006048 if (!Invalid) {
6049 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6050 // C++ [except.handle]p16:
6051 // The object declared in an exception-declaration or, if the
6052 // exception-declaration does not specify a name, a temporary (12.2) is
6053 // copy-initialized (8.5) from the exception object. [...]
6054 // The object is destroyed when the handler exits, after the destruction
6055 // of any automatic objects initialized within the handler.
6056 //
6057 // We just pretend to initialize the object with itself, then make sure
6058 // it can be destroyed later.
6059 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6060 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6061 Loc, ExDeclType, 0);
6062 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6063 SourceLocation());
6064 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006065 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006066 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006067 if (Result.isInvalid())
6068 Invalid = true;
6069 else
6070 FinalizeVarWithDestructor(ExDecl, RecordTy);
6071 }
6072 }
6073
Douglas Gregord308e622009-05-18 20:51:54 +00006074 if (Invalid)
6075 ExDecl->setInvalidDecl();
6076
6077 return ExDecl;
6078}
6079
6080/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6081/// handler.
John McCalld226f652010-08-21 09:40:31 +00006082Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006083 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6084 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006085
6086 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006087 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006088 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006089 LookupOrdinaryName,
6090 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006091 // The scope should be freshly made just for us. There is just no way
6092 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006093 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006094 if (PrevDecl->isTemplateParameter()) {
6095 // Maybe we will complain about the shadowed template parameter.
6096 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006097 }
6098 }
6099
Chris Lattnereaaebc72009-04-25 08:06:05 +00006100 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006101 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6102 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006103 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006104 }
6105
Douglas Gregor83cb9422010-09-09 17:09:21 +00006106 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006107 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006108 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006109
Chris Lattnereaaebc72009-04-25 08:06:05 +00006110 if (Invalid)
6111 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006112
Sebastian Redl4b07b292008-12-22 19:15:10 +00006113 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006114 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006115 PushOnScopeChains(ExDecl, S);
6116 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006117 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006118
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006119 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006120 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006121}
Anders Carlssonfb311762009-03-14 00:25:26 +00006122
John McCalld226f652010-08-21 09:40:31 +00006123Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006124 Expr *AssertExpr,
6125 Expr *AssertMessageExpr_) {
6126 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006127
Anders Carlssonc3082412009-03-14 00:33:21 +00006128 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6129 llvm::APSInt Value(32);
6130 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6131 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6132 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006133 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006134 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006135
Anders Carlssonc3082412009-03-14 00:33:21 +00006136 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006137 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006138 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006139 }
6140 }
Mike Stump1eb44332009-09-09 15:08:12 +00006141
Mike Stump1eb44332009-09-09 15:08:12 +00006142 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006143 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006144
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006145 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006146 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006147}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006148
Douglas Gregor1d869352010-04-07 16:53:43 +00006149/// \brief Perform semantic analysis of the given friend type declaration.
6150///
6151/// \returns A friend declaration that.
6152FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6153 TypeSourceInfo *TSInfo) {
6154 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6155
6156 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006157 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006158
Douglas Gregor06245bf2010-04-07 17:57:12 +00006159 if (!getLangOptions().CPlusPlus0x) {
6160 // C++03 [class.friend]p2:
6161 // An elaborated-type-specifier shall be used in a friend declaration
6162 // for a class.*
6163 //
6164 // * The class-key of the elaborated-type-specifier is required.
6165 if (!ActiveTemplateInstantiations.empty()) {
6166 // Do not complain about the form of friend template types during
6167 // template instantiation; we will already have complained when the
6168 // template was declared.
6169 } else if (!T->isElaboratedTypeSpecifier()) {
6170 // If we evaluated the type to a record type, suggest putting
6171 // a tag in front.
6172 if (const RecordType *RT = T->getAs<RecordType>()) {
6173 RecordDecl *RD = RT->getDecl();
6174
6175 std::string InsertionText = std::string(" ") + RD->getKindName();
6176
6177 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6178 << (unsigned) RD->getTagKind()
6179 << T
6180 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6181 InsertionText);
6182 } else {
6183 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6184 << T
6185 << SourceRange(FriendLoc, TypeRange.getEnd());
6186 }
6187 } else if (T->getAs<EnumType>()) {
6188 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006189 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006190 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006191 }
6192 }
6193
Douglas Gregor06245bf2010-04-07 17:57:12 +00006194 // C++0x [class.friend]p3:
6195 // If the type specifier in a friend declaration designates a (possibly
6196 // cv-qualified) class type, that class is declared as a friend; otherwise,
6197 // the friend declaration is ignored.
6198
6199 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6200 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006201
6202 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6203}
6204
John McCalldd4a3b02009-09-16 22:47:08 +00006205/// Handle a friend type declaration. This works in tandem with
6206/// ActOnTag.
6207///
6208/// Notes on friend class templates:
6209///
6210/// We generally treat friend class declarations as if they were
6211/// declaring a class. So, for example, the elaborated type specifier
6212/// in a friend declaration is required to obey the restrictions of a
6213/// class-head (i.e. no typedefs in the scope chain), template
6214/// parameters are required to match up with simple template-ids, &c.
6215/// However, unlike when declaring a template specialization, it's
6216/// okay to refer to a template specialization without an empty
6217/// template parameter declaration, e.g.
6218/// friend class A<T>::B<unsigned>;
6219/// We permit this as a special case; if there are any template
6220/// parameters present at all, require proper matching, i.e.
6221/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006222Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00006223 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006224 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006225
6226 assert(DS.isFriendSpecified());
6227 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6228
John McCalldd4a3b02009-09-16 22:47:08 +00006229 // Try to convert the decl specifier to a type. This works for
6230 // friend templates because ActOnTag never produces a ClassTemplateDecl
6231 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006232 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006233 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6234 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006235 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006236 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006237
John McCalldd4a3b02009-09-16 22:47:08 +00006238 // This is definitely an error in C++98. It's probably meant to
6239 // be forbidden in C++0x, too, but the specification is just
6240 // poorly written.
6241 //
6242 // The problem is with declarations like the following:
6243 // template <T> friend A<T>::foo;
6244 // where deciding whether a class C is a friend or not now hinges
6245 // on whether there exists an instantiation of A that causes
6246 // 'foo' to equal C. There are restrictions on class-heads
6247 // (which we declare (by fiat) elaborated friend declarations to
6248 // be) that makes this tractable.
6249 //
6250 // FIXME: handle "template <> friend class A<T>;", which
6251 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006252 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006253 Diag(Loc, diag::err_tagless_friend_type_template)
6254 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006255 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006256 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006257
John McCall02cace72009-08-28 07:59:38 +00006258 // C++98 [class.friend]p1: A friend of a class is a function
6259 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006260 // This is fixed in DR77, which just barely didn't make the C++03
6261 // deadline. It's also a very silly restriction that seriously
6262 // affects inner classes and which nobody else seems to implement;
6263 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006264 //
6265 // But note that we could warn about it: it's always useless to
6266 // friend one of your own members (it's not, however, worthless to
6267 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006268
John McCalldd4a3b02009-09-16 22:47:08 +00006269 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006270 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006271 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006272 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00006273 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006274 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006275 DS.getFriendSpecLoc());
6276 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006277 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6278
6279 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006280 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006281
John McCalldd4a3b02009-09-16 22:47:08 +00006282 D->setAccess(AS_public);
6283 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006284
John McCalld226f652010-08-21 09:40:31 +00006285 return D;
John McCall02cace72009-08-28 07:59:38 +00006286}
6287
John McCall337ec3d2010-10-12 23:13:28 +00006288Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6289 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006290 const DeclSpec &DS = D.getDeclSpec();
6291
6292 assert(DS.isFriendSpecified());
6293 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6294
6295 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006296 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6297 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006298
6299 // C++ [class.friend]p1
6300 // A friend of a class is a function or class....
6301 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006302 // It *doesn't* see through dependent types, which is correct
6303 // according to [temp.arg.type]p3:
6304 // If a declaration acquires a function type through a
6305 // type dependent on a template-parameter and this causes
6306 // a declaration that does not use the syntactic form of a
6307 // function declarator to have a function type, the program
6308 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006309 if (!T->isFunctionType()) {
6310 Diag(Loc, diag::err_unexpected_friend);
6311
6312 // It might be worthwhile to try to recover by creating an
6313 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006314 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006315 }
6316
6317 // C++ [namespace.memdef]p3
6318 // - If a friend declaration in a non-local class first declares a
6319 // class or function, the friend class or function is a member
6320 // of the innermost enclosing namespace.
6321 // - The name of the friend is not found by simple name lookup
6322 // until a matching declaration is provided in that namespace
6323 // scope (either before or after the class declaration granting
6324 // friendship).
6325 // - If a friend function is called, its name may be found by the
6326 // name lookup that considers functions from namespaces and
6327 // classes associated with the types of the function arguments.
6328 // - When looking for a prior declaration of a class or a function
6329 // declared as a friend, scopes outside the innermost enclosing
6330 // namespace scope are not considered.
6331
John McCall337ec3d2010-10-12 23:13:28 +00006332 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006333 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6334 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006335 assert(Name);
6336
John McCall67d1a672009-08-06 02:15:43 +00006337 // The context we found the declaration in, or in which we should
6338 // create the declaration.
6339 DeclContext *DC;
Abramo Bagnara25777432010-08-11 22:01:17 +00006340 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006341 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006342
John McCall337ec3d2010-10-12 23:13:28 +00006343 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006344
John McCall337ec3d2010-10-12 23:13:28 +00006345 // There are four cases here.
6346 // - There's no scope specifier, in which case we just go to the
6347 // appropriate namespace and create a function or function template
6348 // there as appropriate.
6349 // Recover from invalid scope qualifiers as if they just weren't there.
6350 if (SS.isInvalid() || !SS.isSet()) {
6351 // Walk out to the nearest namespace scope looking for matches.
John McCall67d1a672009-08-06 02:15:43 +00006352
6353 DC = CurContext;
6354 while (true) {
6355 // Skip class contexts. If someone can cite chapter and verse
6356 // for this behavior, that would be nice --- it's what GCC and
6357 // EDG do, and it seems like a reasonable intent, but the spec
6358 // really only says that checks for unqualified existing
6359 // declarations should stop at the nearest enclosing namespace,
6360 // not that they should only consider the nearest enclosing
6361 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006362 while (DC->isRecord())
6363 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006364
John McCall68263142009-11-18 22:49:29 +00006365 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006366
6367 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00006368 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006369 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00006370
John McCall67d1a672009-08-06 02:15:43 +00006371 if (DC->isFileContext()) break;
6372 DC = DC->getParent();
6373 }
6374
6375 // C++ [class.friend]p1: A friend of a class is a function or
6376 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006377 // C++0x changes this for both friend types and functions.
6378 // Most C++ 98 compilers do seem to give an error here, so
6379 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006380 if (!Previous.empty() && DC->Equals(CurContext)
6381 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006382 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006383
6384 // - There's a non-dependent scope specifier, in which case we
6385 // compute it and do a previous lookup there for a function
6386 // or function template.
6387 } else if (!SS.getScopeRep()->isDependent()) {
6388 DC = computeDeclContext(SS);
6389 if (!DC) return 0;
6390
6391 if (RequireCompleteDeclContext(SS, DC)) return 0;
6392
6393 LookupQualifiedName(Previous, DC);
6394
6395 // Ignore things found implicitly in the wrong scope.
6396 // TODO: better diagnostics for this case. Suggesting the right
6397 // qualified scope would be nice...
6398 LookupResult::Filter F = Previous.makeFilter();
6399 while (F.hasNext()) {
6400 NamedDecl *D = F.next();
6401 if (!DC->InEnclosingNamespaceSetOf(
6402 D->getDeclContext()->getRedeclContext()))
6403 F.erase();
6404 }
6405 F.done();
6406
6407 if (Previous.empty()) {
6408 D.setInvalidType();
6409 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6410 return 0;
6411 }
6412
6413 // C++ [class.friend]p1: A friend of a class is a function or
6414 // class that is not a member of the class . . .
6415 if (DC->Equals(CurContext))
6416 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6417
6418 // - There's a scope specifier that does not match any template
6419 // parameter lists, in which case we use some arbitrary context,
6420 // create a method or method template, and wait for instantiation.
6421 // - There's a scope specifier that does match some template
6422 // parameter lists, which we don't handle right now.
6423 } else {
6424 DC = CurContext;
6425 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006426 }
6427
Douglas Gregor182ddf02009-09-28 00:08:27 +00006428 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00006429 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006430 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6431 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6432 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006433 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006434 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6435 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006436 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006437 }
John McCall67d1a672009-08-06 02:15:43 +00006438 }
6439
Douglas Gregor182ddf02009-09-28 00:08:27 +00006440 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00006441 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006442 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006443 IsDefinition,
6444 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006445 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006446
Douglas Gregor182ddf02009-09-28 00:08:27 +00006447 assert(ND->getDeclContext() == DC);
6448 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006449
John McCallab88d972009-08-31 22:39:49 +00006450 // Add the function declaration to the appropriate lookup tables,
6451 // adjusting the redeclarations list as necessary. We don't
6452 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006453 //
John McCallab88d972009-08-31 22:39:49 +00006454 // Also update the scope-based lookup if the target context's
6455 // lookup context is in lexical scope.
6456 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006457 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006458 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006459 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006460 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006461 }
John McCall02cace72009-08-28 07:59:38 +00006462
6463 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006464 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006465 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006466 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006467 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006468
John McCall337ec3d2010-10-12 23:13:28 +00006469 if (ND->isInvalidDecl())
6470 FrD->setInvalidDecl();
6471
John McCalld226f652010-08-21 09:40:31 +00006472 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006473}
6474
John McCalld226f652010-08-21 09:40:31 +00006475void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6476 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006477
Sebastian Redl50de12f2009-03-24 22:27:57 +00006478 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6479 if (!Fn) {
6480 Diag(DelLoc, diag::err_deleted_non_function);
6481 return;
6482 }
6483 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6484 Diag(DelLoc, diag::err_deleted_decl_not_first);
6485 Diag(Prev->getLocation(), diag::note_previous_declaration);
6486 // If the declaration wasn't the first, we delete the function anyway for
6487 // recovery.
6488 }
6489 Fn->setDeleted();
6490}
Sebastian Redl13e88542009-04-27 21:33:24 +00006491
6492static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6493 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6494 ++CI) {
6495 Stmt *SubStmt = *CI;
6496 if (!SubStmt)
6497 continue;
6498 if (isa<ReturnStmt>(SubStmt))
6499 Self.Diag(SubStmt->getSourceRange().getBegin(),
6500 diag::err_return_in_constructor_handler);
6501 if (!isa<Expr>(SubStmt))
6502 SearchForReturnInStmt(Self, SubStmt);
6503 }
6504}
6505
6506void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6507 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6508 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6509 SearchForReturnInStmt(*this, Handler);
6510 }
6511}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006512
Mike Stump1eb44332009-09-09 15:08:12 +00006513bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006514 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006515 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6516 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006517
Chandler Carruth73857792010-02-15 11:53:20 +00006518 if (Context.hasSameType(NewTy, OldTy) ||
6519 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006520 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006521
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006522 // Check if the return types are covariant
6523 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006524
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006525 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006526 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6527 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006528 NewClassTy = NewPT->getPointeeType();
6529 OldClassTy = OldPT->getPointeeType();
6530 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006531 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6532 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6533 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6534 NewClassTy = NewRT->getPointeeType();
6535 OldClassTy = OldRT->getPointeeType();
6536 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006537 }
6538 }
Mike Stump1eb44332009-09-09 15:08:12 +00006539
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006540 // The return types aren't either both pointers or references to a class type.
6541 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006542 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006543 diag::err_different_return_type_for_overriding_virtual_function)
6544 << New->getDeclName() << NewTy << OldTy;
6545 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006546
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006547 return true;
6548 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006549
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006550 // C++ [class.virtual]p6:
6551 // If the return type of D::f differs from the return type of B::f, the
6552 // class type in the return type of D::f shall be complete at the point of
6553 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006554 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6555 if (!RT->isBeingDefined() &&
6556 RequireCompleteType(New->getLocation(), NewClassTy,
6557 PDiag(diag::err_covariant_return_incomplete)
6558 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006559 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006560 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006561
Douglas Gregora4923eb2009-11-16 21:35:15 +00006562 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006563 // Check if the new class derives from the old class.
6564 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6565 Diag(New->getLocation(),
6566 diag::err_covariant_return_not_derived)
6567 << New->getDeclName() << NewTy << OldTy;
6568 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6569 return true;
6570 }
Mike Stump1eb44332009-09-09 15:08:12 +00006571
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006572 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006573 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006574 diag::err_covariant_return_inaccessible_base,
6575 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6576 // FIXME: Should this point to the return type?
6577 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006578 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6579 return true;
6580 }
6581 }
Mike Stump1eb44332009-09-09 15:08:12 +00006582
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006583 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006584 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006585 Diag(New->getLocation(),
6586 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006587 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006588 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6589 return true;
6590 };
Mike Stump1eb44332009-09-09 15:08:12 +00006591
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006592
6593 // The new class type must have the same or less qualifiers as the old type.
6594 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6595 Diag(New->getLocation(),
6596 diag::err_covariant_return_type_class_type_more_qualified)
6597 << New->getDeclName() << NewTy << OldTy;
6598 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6599 return true;
6600 };
Mike Stump1eb44332009-09-09 15:08:12 +00006601
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006602 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006603}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006604
Sean Huntbbd37c62009-11-21 08:43:09 +00006605bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6606 const CXXMethodDecl *Old)
6607{
6608 if (Old->hasAttr<FinalAttr>()) {
6609 Diag(New->getLocation(), diag::err_final_function_overridden)
6610 << New->getDeclName();
6611 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6612 return true;
6613 }
6614
6615 return false;
6616}
6617
Douglas Gregor4ba31362009-12-01 17:24:26 +00006618/// \brief Mark the given method pure.
6619///
6620/// \param Method the method to be marked pure.
6621///
6622/// \param InitRange the source range that covers the "0" initializer.
6623bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6624 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6625 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006626 return false;
6627 }
6628
6629 if (!Method->isInvalidDecl())
6630 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6631 << Method->getDeclName() << InitRange;
6632 return true;
6633}
6634
John McCall731ad842009-12-19 09:28:58 +00006635/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6636/// an initializer for the out-of-line declaration 'Dcl'. The scope
6637/// is a fresh scope pushed for just this purpose.
6638///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006639/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6640/// static data member of class X, names should be looked up in the scope of
6641/// class X.
John McCalld226f652010-08-21 09:40:31 +00006642void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006643 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006644 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006645
John McCall731ad842009-12-19 09:28:58 +00006646 // We should only get called for declarations with scope specifiers, like:
6647 // int foo::bar;
6648 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006649 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006650}
6651
6652/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006653/// initializer for the out-of-line declaration 'D'.
6654void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006655 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006656 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006657
John McCall731ad842009-12-19 09:28:58 +00006658 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006659 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006660}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006661
6662/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6663/// C++ if/switch/while/for statement.
6664/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006665DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006666 // C++ 6.4p2:
6667 // The declarator shall not specify a function or an array.
6668 // The type-specifier-seq shall not contain typedef and shall not declare a
6669 // new class or enumeration.
6670 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6671 "Parser allowed 'typedef' as storage class of condition decl.");
6672
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006673 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006674 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6675 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006676
6677 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6678 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6679 // would be created and CXXConditionDeclExpr wants a VarDecl.
6680 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6681 << D.getSourceRange();
6682 return DeclResult();
6683 } else if (OwnedTag && OwnedTag->isDefinition()) {
6684 // The type-specifier-seq shall not declare a new class or enumeration.
6685 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6686 }
6687
John McCalld226f652010-08-21 09:40:31 +00006688 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006689 if (!Dcl)
6690 return DeclResult();
6691
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006692 return Dcl;
6693}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006694
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006695void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6696 bool DefinitionRequired) {
6697 // Ignore any vtable uses in unevaluated operands or for classes that do
6698 // not have a vtable.
6699 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6700 CurContext->isDependentContext() ||
6701 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006702 return;
6703
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006704 // Try to insert this class into the map.
6705 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6706 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6707 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6708 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006709 // If we already had an entry, check to see if we are promoting this vtable
6710 // to required a definition. If so, we need to reappend to the VTableUses
6711 // list, since we may have already processed the first entry.
6712 if (DefinitionRequired && !Pos.first->second) {
6713 Pos.first->second = true;
6714 } else {
6715 // Otherwise, we can early exit.
6716 return;
6717 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006718 }
6719
6720 // Local classes need to have their virtual members marked
6721 // immediately. For all other classes, we mark their virtual members
6722 // at the end of the translation unit.
6723 if (Class->isLocalClass())
6724 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006725 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006726 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006727}
6728
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006729bool Sema::DefineUsedVTables() {
6730 // If any dynamic classes have their key function defined within
6731 // this translation unit, then those vtables are considered "used" and must
6732 // be emitted.
6733 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6734 if (const CXXMethodDecl *KeyFunction
6735 = Context.getKeyFunction(DynamicClasses[I])) {
6736 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006737 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006738 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6739 }
6740 }
6741
6742 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006743 return false;
6744
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006745 // Note: The VTableUses vector could grow as a result of marking
6746 // the members of a class as "used", so we check the size each
6747 // time through the loop and prefer indices (with are stable) to
6748 // iterators (which are not).
6749 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006750 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006751 if (!Class)
6752 continue;
6753
6754 SourceLocation Loc = VTableUses[I].second;
6755
6756 // If this class has a key function, but that key function is
6757 // defined in another translation unit, we don't need to emit the
6758 // vtable even though we're using it.
6759 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006760 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006761 switch (KeyFunction->getTemplateSpecializationKind()) {
6762 case TSK_Undeclared:
6763 case TSK_ExplicitSpecialization:
6764 case TSK_ExplicitInstantiationDeclaration:
6765 // The key function is in another translation unit.
6766 continue;
6767
6768 case TSK_ExplicitInstantiationDefinition:
6769 case TSK_ImplicitInstantiation:
6770 // We will be instantiating the key function.
6771 break;
6772 }
6773 } else if (!KeyFunction) {
6774 // If we have a class with no key function that is the subject
6775 // of an explicit instantiation declaration, suppress the
6776 // vtable; it will live with the explicit instantiation
6777 // definition.
6778 bool IsExplicitInstantiationDeclaration
6779 = Class->getTemplateSpecializationKind()
6780 == TSK_ExplicitInstantiationDeclaration;
6781 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6782 REnd = Class->redecls_end();
6783 R != REnd; ++R) {
6784 TemplateSpecializationKind TSK
6785 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6786 if (TSK == TSK_ExplicitInstantiationDeclaration)
6787 IsExplicitInstantiationDeclaration = true;
6788 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6789 IsExplicitInstantiationDeclaration = false;
6790 break;
6791 }
6792 }
6793
6794 if (IsExplicitInstantiationDeclaration)
6795 continue;
6796 }
6797
6798 // Mark all of the virtual members of this class as referenced, so
6799 // that we can build a vtable. Then, tell the AST consumer that a
6800 // vtable for this class is required.
6801 MarkVirtualMembersReferenced(Loc, Class);
6802 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6803 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6804
6805 // Optionally warn if we're emitting a weak vtable.
6806 if (Class->getLinkage() == ExternalLinkage &&
6807 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006808 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006809 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6810 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006811 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006812 VTableUses.clear();
6813
Anders Carlssond6a637f2009-12-07 08:24:59 +00006814 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006815}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006816
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006817void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6818 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006819 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6820 e = RD->method_end(); i != e; ++i) {
6821 CXXMethodDecl *MD = *i;
6822
6823 // C++ [basic.def.odr]p2:
6824 // [...] A virtual member function is used if it is not pure. [...]
6825 if (MD->isVirtual() && !MD->isPure())
6826 MarkDeclarationReferenced(Loc, MD);
6827 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006828
6829 // Only classes that have virtual bases need a VTT.
6830 if (RD->getNumVBases() == 0)
6831 return;
6832
6833 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6834 e = RD->bases_end(); i != e; ++i) {
6835 const CXXRecordDecl *Base =
6836 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006837 if (Base->getNumVBases() == 0)
6838 continue;
6839 MarkVirtualMembersReferenced(Loc, Base);
6840 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006841}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006842
6843/// SetIvarInitializers - This routine builds initialization ASTs for the
6844/// Objective-C implementation whose ivars need be initialized.
6845void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6846 if (!getLangOptions().CPlusPlus)
6847 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00006848 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006849 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6850 CollectIvarsToConstructOrDestruct(OID, ivars);
6851 if (ivars.empty())
6852 return;
6853 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6854 for (unsigned i = 0; i < ivars.size(); i++) {
6855 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006856 if (Field->isInvalidDecl())
6857 continue;
6858
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006859 CXXBaseOrMemberInitializer *Member;
6860 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6861 InitializationKind InitKind =
6862 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6863
6864 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006865 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00006866 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00006867 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006868 // Note, MemberInit could actually come back empty if no initialization
6869 // is required (e.g., because it would call a trivial default constructor)
6870 if (!MemberInit.get() || MemberInit.isInvalid())
6871 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00006872
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006873 Member =
6874 new (Context) CXXBaseOrMemberInitializer(Context,
6875 Field, SourceLocation(),
6876 SourceLocation(),
6877 MemberInit.takeAs<Expr>(),
6878 SourceLocation());
6879 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006880
6881 // Be sure that the destructor is accessible and is marked as referenced.
6882 if (const RecordType *RecordTy
6883 = Context.getBaseElementType(Field->getType())
6884 ->getAs<RecordType>()) {
6885 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00006886 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006887 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6888 CheckDestructorAccess(Field->getLocation(), Destructor,
6889 PDiag(diag::err_access_dtor_ivar)
6890 << Context.getBaseElementType(Field->getType()));
6891 }
6892 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006893 }
6894 ObjCImplementation->setIvarInitializers(Context,
6895 AllToInit.data(), AllToInit.size());
6896 }
6897}