blob: 0cf5f99b6448b77b6cedf7156304b93ff167b326 [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.
John McCallb6bbcc92010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
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,
Nico Weber6bb4dcb2010-11-28 22:53:37 +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);
John McCall4765fa02010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(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()
John McCall4765fa02010-12-06 08:20:24 +0000314 // strips off any top-level ExprWithCleanups.
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 Gregord0937222010-12-13 22:49:22 +0000546
547 if (DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
548 UPPC_BaseType))
549 return true;
550
Douglas Gregor2943aed2009-03-03 04:44:36 +0000551 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000552 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000553 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Douglas Gregor2943aed2009-03-03 04:44:36 +0000555 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000556}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000557
Douglas Gregor2943aed2009-03-03 04:44:36 +0000558/// \brief Performs the actual work of attaching the given base class
559/// specifiers to a C++ class.
560bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
561 unsigned NumBases) {
562 if (NumBases == 0)
563 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000564
565 // Used to keep track of which base types we have already seen, so
566 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000567 // that the key is always the unqualified canonical type of the base
568 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000569 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
570
571 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000572 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000574 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000575 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000577 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000578 if (!Class->hasObjectMember()) {
579 if (const RecordType *FDTTy =
580 NewBaseType.getTypePtr()->getAs<RecordType>())
581 if (FDTTy->getDecl()->hasObjectMember())
582 Class->setHasObjectMember(true);
583 }
584
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000585 if (KnownBaseTypes[NewBaseType]) {
586 // C++ [class.mi]p3:
587 // A class shall not be specified as a direct base class of a
588 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000590 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000591 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000592 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000593
594 // Delete the duplicate base class specifier; we're going to
595 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000596 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597
598 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000599 } else {
600 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 KnownBaseTypes[NewBaseType] = Bases[idx];
602 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000603 }
604 }
605
606 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000607 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608
609 // Delete the remaining (good) base class specifiers, since their
610 // data has been copied into the CXXRecordDecl.
611 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000612 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613
614 return Invalid;
615}
616
617/// ActOnBaseSpecifiers - Attach the given base specifiers to the
618/// class, after checking whether there are any duplicate base
619/// classes.
John McCalld226f652010-08-21 09:40:31 +0000620void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 unsigned NumBases) {
622 if (!ClassDecl || !Bases || !NumBases)
623 return;
624
625 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000626 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000628}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000629
John McCall3cb0ebd2010-03-10 03:28:59 +0000630static CXXRecordDecl *GetClassForType(QualType T) {
631 if (const RecordType *RT = T->getAs<RecordType>())
632 return cast<CXXRecordDecl>(RT->getDecl());
633 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
634 return ICT->getDecl();
635 else
636 return 0;
637}
638
Douglas Gregora8f32e02009-10-06 17:59:45 +0000639/// \brief Determine whether the type \p Derived is a C++ class that is
640/// derived from the type \p Base.
641bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
642 if (!getLangOptions().CPlusPlus)
643 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000644
645 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
646 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000647 return false;
648
John McCall3cb0ebd2010-03-10 03:28:59 +0000649 CXXRecordDecl *BaseRD = GetClassForType(Base);
650 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000651 return false;
652
John McCall86ff3082010-02-04 22:26:26 +0000653 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
654 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000655}
656
657/// \brief Determine whether the type \p Derived is a C++ class that is
658/// derived from the type \p Base.
659bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
660 if (!getLangOptions().CPlusPlus)
661 return false;
662
John McCall3cb0ebd2010-03-10 03:28:59 +0000663 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
664 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665 return false;
666
John McCall3cb0ebd2010-03-10 03:28:59 +0000667 CXXRecordDecl *BaseRD = GetClassForType(Base);
668 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000669 return false;
670
Douglas Gregora8f32e02009-10-06 17:59:45 +0000671 return DerivedRD->isDerivedFrom(BaseRD, Paths);
672}
673
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000674void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000675 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000676 assert(BasePathArray.empty() && "Base path array must be empty!");
677 assert(Paths.isRecordingPaths() && "Must record paths!");
678
679 const CXXBasePath &Path = Paths.front();
680
681 // We first go backward and check if we have a virtual base.
682 // FIXME: It would be better if CXXBasePath had the base specifier for
683 // the nearest virtual base.
684 unsigned Start = 0;
685 for (unsigned I = Path.size(); I != 0; --I) {
686 if (Path[I - 1].Base->isVirtual()) {
687 Start = I - 1;
688 break;
689 }
690 }
691
692 // Now add all bases.
693 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000694 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000695}
696
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000697/// \brief Determine whether the given base path includes a virtual
698/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000699bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
700 for (CXXCastPath::const_iterator B = BasePath.begin(),
701 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000702 B != BEnd; ++B)
703 if ((*B)->isVirtual())
704 return true;
705
706 return false;
707}
708
Douglas Gregora8f32e02009-10-06 17:59:45 +0000709/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
710/// conversion (where Derived and Base are class types) is
711/// well-formed, meaning that the conversion is unambiguous (and
712/// that all of the base classes are accessible). Returns true
713/// and emits a diagnostic if the code is ill-formed, returns false
714/// otherwise. Loc is the location where this routine should point to
715/// if there is an error, and Range is the source range to highlight
716/// if there is an error.
717bool
718Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000719 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000720 unsigned AmbigiousBaseConvID,
721 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000722 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000723 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000724 // First, determine whether the path from Derived to Base is
725 // ambiguous. This is slightly more expensive than checking whether
726 // the Derived to Base conversion exists, because here we need to
727 // explore multiple paths to determine if there is an ambiguity.
728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
729 /*DetectVirtual=*/false);
730 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
731 assert(DerivationOkay &&
732 "Can only be used with a derived-to-base conversion");
733 (void)DerivationOkay;
734
735 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000736 if (InaccessibleBaseID) {
737 // Check that the base class can be accessed.
738 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
739 InaccessibleBaseID)) {
740 case AR_inaccessible:
741 return true;
742 case AR_accessible:
743 case AR_dependent:
744 case AR_delayed:
745 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000746 }
John McCall6b2accb2010-02-10 09:31:12 +0000747 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000748
749 // Build a base path if necessary.
750 if (BasePath)
751 BuildBasePathArray(Paths, *BasePath);
752 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000753 }
754
755 // We know that the derived-to-base conversion is ambiguous, and
756 // we're going to produce a diagnostic. Perform the derived-to-base
757 // search just one more time to compute all of the possible paths so
758 // that we can print them out. This is more expensive than any of
759 // the previous derived-to-base checks we've done, but at this point
760 // performance isn't as much of an issue.
761 Paths.clear();
762 Paths.setRecordingPaths(true);
763 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
764 assert(StillOkay && "Can only be used with a derived-to-base conversion");
765 (void)StillOkay;
766
767 // Build up a textual representation of the ambiguous paths, e.g.,
768 // D -> B -> A, that will be used to illustrate the ambiguous
769 // conversions in the diagnostic. We only print one of the paths
770 // to each base class subobject.
771 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
772
773 Diag(Loc, AmbigiousBaseConvID)
774 << Derived << Base << PathDisplayStr << Range << Name;
775 return true;
776}
777
778bool
779Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000780 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000781 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000782 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000783 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000784 IgnoreAccess ? 0
785 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000786 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000787 Loc, Range, DeclarationName(),
788 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000789}
790
791
792/// @brief Builds a string representing ambiguous paths from a
793/// specific derived class to different subobjects of the same base
794/// class.
795///
796/// This function builds a string that can be used in error messages
797/// to show the different paths that one can take through the
798/// inheritance hierarchy to go from the derived class to different
799/// subobjects of a base class. The result looks something like this:
800/// @code
801/// struct D -> struct B -> struct A
802/// struct D -> struct C -> struct A
803/// @endcode
804std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
805 std::string PathDisplayStr;
806 std::set<unsigned> DisplayedPaths;
807 for (CXXBasePaths::paths_iterator Path = Paths.begin();
808 Path != Paths.end(); ++Path) {
809 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
810 // We haven't displayed a path to this particular base
811 // class subobject yet.
812 PathDisplayStr += "\n ";
813 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
814 for (CXXBasePath::const_iterator Element = Path->begin();
815 Element != Path->end(); ++Element)
816 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
817 }
818 }
819
820 return PathDisplayStr;
821}
822
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000823//===----------------------------------------------------------------------===//
824// C++ class member Handling
825//===----------------------------------------------------------------------===//
826
Abramo Bagnara6206d532010-06-05 05:09:32 +0000827/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000828Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
829 SourceLocation ASLoc,
830 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000831 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000832 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000833 ASLoc, ColonLoc);
834 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000835 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000836}
837
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000838/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
839/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
840/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000841/// any.
John McCalld226f652010-08-21 09:40:31 +0000842Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000843Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000844 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000845 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
846 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000847 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000848 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
849 DeclarationName Name = NameInfo.getName();
850 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000851
852 // For anonymous bitfields, the location should point to the type.
853 if (Loc.isInvalid())
854 Loc = D.getSourceRange().getBegin();
855
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000856 Expr *BitWidth = static_cast<Expr*>(BW);
857 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000858
John McCall4bde1e12010-06-04 08:34:12 +0000859 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000860 assert(!DS.isFriendSpecified());
861
John McCall4bde1e12010-06-04 08:34:12 +0000862 bool isFunc = false;
863 if (D.isFunctionDeclarator())
864 isFunc = true;
865 else if (D.getNumTypeObjects() == 0 &&
866 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000867 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000868 isFunc = TDType->isFunctionType();
869 }
870
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000871 // C++ 9.2p6: A member shall not be declared to have automatic storage
872 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000873 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
874 // data members and cannot be applied to names declared const or static,
875 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000876 switch (DS.getStorageClassSpec()) {
877 case DeclSpec::SCS_unspecified:
878 case DeclSpec::SCS_typedef:
879 case DeclSpec::SCS_static:
880 // FALL THROUGH.
881 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000882 case DeclSpec::SCS_mutable:
883 if (isFunc) {
884 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000885 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000886 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000887 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Sebastian Redla11f42f2008-11-17 23:24:37 +0000889 // FIXME: It would be nicer if the keyword was ignored only for this
890 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000891 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000892 }
893 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000894 default:
895 if (DS.getStorageClassSpecLoc().isValid())
896 Diag(DS.getStorageClassSpecLoc(),
897 diag::err_storageclass_invalid_for_member);
898 else
899 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
900 D.getMutableDeclSpec().ClearStorageClassSpecs();
901 }
902
Sebastian Redl669d5d72008-11-14 23:42:31 +0000903 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
904 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000905 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000906
907 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000908 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000909 CXXScopeSpec &SS = D.getCXXScopeSpec();
910
911
912 if (SS.isSet() && !SS.isInvalid()) {
913 // The user provided a superfluous scope specifier inside a class
914 // definition:
915 //
916 // class X {
917 // int X::member;
918 // };
919 DeclContext *DC = 0;
920 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
921 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
922 << Name << FixItHint::CreateRemoval(SS.getRange());
923 else
924 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
925 << Name << SS.getRange();
926
927 SS.clear();
928 }
929
Douglas Gregor37b372b2009-08-20 22:52:58 +0000930 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +0000931 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000932 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
933 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000934 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000935 } else {
John McCalld226f652010-08-21 09:40:31 +0000936 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000937 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000938 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000939 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000940
941 // Non-instance-fields can't have a bitfield.
942 if (BitWidth) {
943 if (Member->isInvalidDecl()) {
944 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000945 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000946 // C++ 9.6p3: A bit-field shall not be a static member.
947 // "static member 'A' cannot be a bit-field"
948 Diag(Loc, diag::err_static_not_bitfield)
949 << Name << BitWidth->getSourceRange();
950 } else if (isa<TypedefDecl>(Member)) {
951 // "typedef member 'x' cannot be a bit-field"
952 Diag(Loc, diag::err_typedef_not_bitfield)
953 << Name << BitWidth->getSourceRange();
954 } else {
955 // A function typedef ("typedef int f(); f a;").
956 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
957 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000958 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000959 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner8b963ef2009-03-05 23:01:03 +0000962 BitWidth = 0;
963 Member->setInvalidDecl();
964 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000965
966 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Douglas Gregor37b372b2009-08-20 22:52:58 +0000968 // If we have declared a member function template, set the access of the
969 // templated declaration as well.
970 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
971 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000972 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000973
Douglas Gregor10bd3682008-11-17 22:58:34 +0000974 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000975
Douglas Gregor021c3b32009-03-11 23:00:04 +0000976 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +0000977 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000978 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +0000979 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000980
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000981 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000982 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +0000983 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000984 }
John McCalld226f652010-08-21 09:40:31 +0000985 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000986}
987
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000988/// \brief Find the direct and/or virtual base specifiers that
989/// correspond to the given base type, for use in base initialization
990/// within a constructor.
991static bool FindBaseInitializer(Sema &SemaRef,
992 CXXRecordDecl *ClassDecl,
993 QualType BaseType,
994 const CXXBaseSpecifier *&DirectBaseSpec,
995 const CXXBaseSpecifier *&VirtualBaseSpec) {
996 // First, check for a direct base class.
997 DirectBaseSpec = 0;
998 for (CXXRecordDecl::base_class_const_iterator Base
999 = ClassDecl->bases_begin();
1000 Base != ClassDecl->bases_end(); ++Base) {
1001 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1002 // We found a direct base of this type. That's what we're
1003 // initializing.
1004 DirectBaseSpec = &*Base;
1005 break;
1006 }
1007 }
1008
1009 // Check for a virtual base class.
1010 // FIXME: We might be able to short-circuit this if we know in advance that
1011 // there are no virtual bases.
1012 VirtualBaseSpec = 0;
1013 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1014 // We haven't found a base yet; search the class hierarchy for a
1015 // virtual base class.
1016 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1017 /*DetectVirtual=*/false);
1018 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1019 BaseType, Paths)) {
1020 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1021 Path != Paths.end(); ++Path) {
1022 if (Path->back().Base->isVirtual()) {
1023 VirtualBaseSpec = Path->back().Base;
1024 break;
1025 }
1026 }
1027 }
1028 }
1029
1030 return DirectBaseSpec || VirtualBaseSpec;
1031}
1032
Douglas Gregor7ad83902008-11-05 04:29:56 +00001033/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001034MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001035Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001036 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001037 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001038 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001039 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001040 SourceLocation IdLoc,
1041 SourceLocation LParenLoc,
1042 ExprTy **Args, unsigned NumArgs,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001043 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001044 if (!ConstructorD)
1045 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001047 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001048
1049 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001050 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001051 if (!Constructor) {
1052 // The user wrote a constructor initializer on a function that is
1053 // not a C++ constructor. Ignore the error for now, because we may
1054 // have more member initializers coming; we'll diagnose it just
1055 // once in ActOnMemInitializers.
1056 return true;
1057 }
1058
1059 CXXRecordDecl *ClassDecl = Constructor->getParent();
1060
1061 // C++ [class.base.init]p2:
1062 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001063 // constructor's class and, if not found in that scope, are looked
1064 // up in the scope containing the constructor's definition.
1065 // [Note: if the constructor's class contains a member with the
1066 // same name as a direct or virtual base class of the class, a
1067 // mem-initializer-id naming the member or base class and composed
1068 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001069 // mem-initializer-id for the hidden base class may be specified
1070 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001071 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001072 // Look for a member, first.
1073 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001074 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001075 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001076 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001077 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001078
Francois Pichet00eb3f92010-12-04 09:14:42 +00001079 if (Member)
1080 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001081 LParenLoc, RParenLoc);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001082 // Handle anonymous union case.
1083 if (IndirectFieldDecl* IndirectField
1084 = dyn_cast<IndirectFieldDecl>(*Result.first))
1085 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1086 NumArgs, IdLoc,
1087 LParenLoc, RParenLoc);
1088 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001089 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001090 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001091 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001092 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001093
1094 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001095 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001096 } else {
1097 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1098 LookupParsedName(R, S, &SS);
1099
1100 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1101 if (!TyD) {
1102 if (R.isAmbiguous()) return true;
1103
John McCallfd225442010-04-09 19:01:14 +00001104 // We don't want access-control diagnostics here.
1105 R.suppressDiagnostics();
1106
Douglas Gregor7a886e12010-01-19 06:46:48 +00001107 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1108 bool NotUnknownSpecialization = false;
1109 DeclContext *DC = computeDeclContext(SS, false);
1110 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1111 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1112
1113 if (!NotUnknownSpecialization) {
1114 // When the scope specifier can refer to a member of an unknown
1115 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001116 BaseType = CheckTypenameType(ETK_None,
1117 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001118 *MemberOrBase, SourceLocation(),
1119 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001120 if (BaseType.isNull())
1121 return true;
1122
Douglas Gregor7a886e12010-01-19 06:46:48 +00001123 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001124 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001125 }
1126 }
1127
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001128 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001129 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001130 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1131 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001132 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001133 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001134 // We have found a non-static data member with a similar
1135 // name to what was typed; complain and initialize that
1136 // member.
1137 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1138 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001139 << FixItHint::CreateReplacement(R.getNameLoc(),
1140 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001141 Diag(Member->getLocation(), diag::note_previous_decl)
1142 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001143
1144 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1145 LParenLoc, RParenLoc);
1146 }
1147 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1148 const CXXBaseSpecifier *DirectBaseSpec;
1149 const CXXBaseSpecifier *VirtualBaseSpec;
1150 if (FindBaseInitializer(*this, ClassDecl,
1151 Context.getTypeDeclType(Type),
1152 DirectBaseSpec, VirtualBaseSpec)) {
1153 // We have found a direct or virtual base class with a
1154 // similar name to what was typed; complain and initialize
1155 // that base class.
1156 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1157 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001158 << FixItHint::CreateReplacement(R.getNameLoc(),
1159 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001160
1161 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1162 : VirtualBaseSpec;
1163 Diag(BaseSpec->getSourceRange().getBegin(),
1164 diag::note_base_class_specified_here)
1165 << BaseSpec->getType()
1166 << BaseSpec->getSourceRange();
1167
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001168 TyD = Type;
1169 }
1170 }
1171 }
1172
Douglas Gregor7a886e12010-01-19 06:46:48 +00001173 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001174 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1175 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1176 return true;
1177 }
John McCall2b194412009-12-21 10:41:20 +00001178 }
1179
Douglas Gregor7a886e12010-01-19 06:46:48 +00001180 if (BaseType.isNull()) {
1181 BaseType = Context.getTypeDeclType(TyD);
1182 if (SS.isSet()) {
1183 NestedNameSpecifier *Qualifier =
1184 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001185
Douglas Gregor7a886e12010-01-19 06:46:48 +00001186 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001187 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001188 }
John McCall2b194412009-12-21 10:41:20 +00001189 }
1190 }
Mike Stump1eb44332009-09-09 15:08:12 +00001191
John McCalla93c9342009-12-07 02:54:59 +00001192 if (!TInfo)
1193 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001194
John McCalla93c9342009-12-07 02:54:59 +00001195 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001196 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001197}
1198
John McCallb4190042009-11-04 23:02:40 +00001199/// Checks an initializer expression for use of uninitialized fields, such as
1200/// containing the field that is being initialized. Returns true if there is an
1201/// uninitialized field was used an updates the SourceLocation parameter; false
1202/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001203static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001204 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001205 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001206 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1207
Nick Lewycky43ad1822010-06-15 07:32:55 +00001208 if (isa<CallExpr>(S)) {
1209 // Do not descend into function calls or constructors, as the use
1210 // of an uninitialized field may be valid. One would have to inspect
1211 // the contents of the function/ctor to determine if it is safe or not.
1212 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1213 // may be safe, depending on what the function/ctor does.
1214 return false;
1215 }
1216 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1217 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001218
1219 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1220 // The member expression points to a static data member.
1221 assert(VD->isStaticDataMember() &&
1222 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001223 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001224 return false;
1225 }
1226
1227 if (isa<EnumConstantDecl>(RhsField)) {
1228 // The member expression points to an enum.
1229 return false;
1230 }
1231
John McCallb4190042009-11-04 23:02:40 +00001232 if (RhsField == LhsField) {
1233 // Initializing a field with itself. Throw a warning.
1234 // But wait; there are exceptions!
1235 // Exception #1: The field may not belong to this record.
1236 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001237 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001238 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1239 // Even though the field matches, it does not belong to this record.
1240 return false;
1241 }
1242 // None of the exceptions triggered; return true to indicate an
1243 // uninitialized field was used.
1244 *L = ME->getMemberLoc();
1245 return true;
1246 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001247 } else if (isa<SizeOfAlignOfExpr>(S)) {
1248 // sizeof/alignof doesn't reference contents, do not warn.
1249 return false;
1250 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1251 // address-of doesn't reference contents (the pointer may be dereferenced
1252 // in the same expression but it would be rare; and weird).
1253 if (UOE->getOpcode() == UO_AddrOf)
1254 return false;
John McCallb4190042009-11-04 23:02:40 +00001255 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001256 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1257 it != e; ++it) {
1258 if (!*it) {
1259 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001260 continue;
1261 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001262 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1263 return true;
John McCallb4190042009-11-04 23:02:40 +00001264 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001265 return false;
John McCallb4190042009-11-04 23:02:40 +00001266}
1267
John McCallf312b1e2010-08-26 23:41:50 +00001268MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001269Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001270 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001271 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001272 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001273 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1274 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1275 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001276 "Member must be a FieldDecl or IndirectFieldDecl");
1277
Douglas Gregor464b2f02010-11-05 22:21:31 +00001278 if (Member->isInvalidDecl())
1279 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001280
John McCallb4190042009-11-04 23:02:40 +00001281 // Diagnose value-uses of fields to initialize themselves, e.g.
1282 // foo(foo)
1283 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001284 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001285 for (unsigned i = 0; i < NumArgs; ++i) {
1286 SourceLocation L;
1287 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1288 // FIXME: Return true in the case when other fields are used before being
1289 // uninitialized. For example, let this field be the i'th field. When
1290 // initializing the i'th field, throw a warning if any of the >= i'th
1291 // fields are used, as they are not yet initialized.
1292 // Right now we are only handling the case where the i'th field uses
1293 // itself in its initializer.
1294 Diag(L, diag::warn_field_is_uninit);
1295 }
1296 }
1297
Eli Friedman59c04372009-07-29 19:44:27 +00001298 bool HasDependentArg = false;
1299 for (unsigned i = 0; i < NumArgs; i++)
1300 HasDependentArg |= Args[i]->isTypeDependent();
1301
Chandler Carruth894aed92010-12-06 09:23:57 +00001302 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001303 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001304 // Can't check initialization for a member of dependent type or when
1305 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001306 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1307 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001308
1309 // Erase any temporaries within this evaluation context; we're not
1310 // going to track them in the AST, since we'll be rebuilding the
1311 // ASTs during template instantiation.
1312 ExprTemporaries.erase(
1313 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1314 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001315 } else {
1316 // Initialize the member.
1317 InitializedEntity MemberEntity =
1318 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1319 : InitializedEntity::InitializeMember(IndirectMember, 0);
1320 InitializationKind Kind =
1321 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001322
Chandler Carruth894aed92010-12-06 09:23:57 +00001323 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1324
1325 ExprResult MemberInit =
1326 InitSeq.Perform(*this, MemberEntity, Kind,
1327 MultiExprArg(*this, Args, NumArgs), 0);
1328 if (MemberInit.isInvalid())
1329 return true;
1330
1331 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1332
1333 // C++0x [class.base.init]p7:
1334 // The initialization of each base and member constitutes a
1335 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001336 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001337 if (MemberInit.isInvalid())
1338 return true;
1339
1340 // If we are in a dependent context, template instantiation will
1341 // perform this type-checking again. Just save the arguments that we
1342 // received in a ParenListExpr.
1343 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1344 // of the information that we have about the member
1345 // initializer. However, deconstructing the ASTs is a dicey process,
1346 // and this approach is far more likely to get the corner cases right.
1347 if (CurContext->isDependentContext())
1348 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1349 RParenLoc);
1350 else
1351 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001352 }
1353
Chandler Carruth894aed92010-12-06 09:23:57 +00001354 if (DirectMember) {
1355 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember,
1356 IdLoc, LParenLoc, Init,
1357 RParenLoc);
1358 } else {
1359 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember,
1360 IdLoc, LParenLoc, Init,
1361 RParenLoc);
1362 }
Eli Friedman59c04372009-07-29 19:44:27 +00001363}
1364
John McCallf312b1e2010-08-26 23:41:50 +00001365MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001366Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001367 Expr **Args, unsigned NumArgs,
1368 SourceLocation LParenLoc, SourceLocation RParenLoc,
1369 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001370 bool HasDependentArg = false;
1371 for (unsigned i = 0; i < NumArgs; i++)
1372 HasDependentArg |= Args[i]->isTypeDependent();
1373
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001374 SourceLocation BaseLoc
1375 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1376
1377 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1378 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1379 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1380
1381 // C++ [class.base.init]p2:
1382 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001383 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001384 // of that class, the mem-initializer is ill-formed. A
1385 // mem-initializer-list can initialize a base class using any
1386 // name that denotes that base class type.
1387 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1388
1389 // Check for direct and virtual base classes.
1390 const CXXBaseSpecifier *DirectBaseSpec = 0;
1391 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1392 if (!Dependent) {
1393 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1394 VirtualBaseSpec);
1395
1396 // C++ [base.class.init]p2:
1397 // Unless the mem-initializer-id names a nonstatic data member of the
1398 // constructor's class or a direct or virtual base of that class, the
1399 // mem-initializer is ill-formed.
1400 if (!DirectBaseSpec && !VirtualBaseSpec) {
1401 // If the class has any dependent bases, then it's possible that
1402 // one of those types will resolve to the same type as
1403 // BaseType. Therefore, just treat this as a dependent base
1404 // class initialization. FIXME: Should we try to check the
1405 // initialization anyway? It seems odd.
1406 if (ClassDecl->hasAnyDependentBases())
1407 Dependent = true;
1408 else
1409 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1410 << BaseType << Context.getTypeDeclType(ClassDecl)
1411 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1412 }
1413 }
1414
1415 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416 // Can't check initialization for a base of dependent type or when
1417 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001418 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001419 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1420 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001421
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001422 // Erase any temporaries within this evaluation context; we're not
1423 // going to track them in the AST, since we'll be rebuilding the
1424 // ASTs during template instantiation.
1425 ExprTemporaries.erase(
1426 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1427 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001429 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001430 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001431 LParenLoc,
1432 BaseInit.takeAs<Expr>(),
1433 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001434 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001435
1436 // C++ [base.class.init]p2:
1437 // If a mem-initializer-id is ambiguous because it designates both
1438 // a direct non-virtual base class and an inherited virtual base
1439 // class, the mem-initializer is ill-formed.
1440 if (DirectBaseSpec && VirtualBaseSpec)
1441 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001442 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001443
1444 CXXBaseSpecifier *BaseSpec
1445 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1446 if (!BaseSpec)
1447 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1448
1449 // Initialize the base.
1450 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001451 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001452 InitializationKind Kind =
1453 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1454
1455 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1456
John McCall60d7b3a2010-08-24 06:29:42 +00001457 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001458 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001459 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001460 if (BaseInit.isInvalid())
1461 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001462
1463 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001464
1465 // C++0x [class.base.init]p7:
1466 // The initialization of each base and member constitutes a
1467 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001468 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001469 if (BaseInit.isInvalid())
1470 return true;
1471
1472 // If we are in a dependent context, template instantiation will
1473 // perform this type-checking again. Just save the arguments that we
1474 // received in a ParenListExpr.
1475 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1476 // of the information that we have about the base
1477 // initializer. However, deconstructing the ASTs is a dicey process,
1478 // and this approach is far more likely to get the corner cases right.
1479 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001480 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001481 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1482 RParenLoc));
1483 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001484 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001485 LParenLoc,
1486 Init.takeAs<Expr>(),
1487 RParenLoc);
1488 }
1489
1490 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001491 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001492 LParenLoc,
1493 BaseInit.takeAs<Expr>(),
1494 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001495}
1496
Anders Carlssone5ef7402010-04-23 03:10:23 +00001497/// ImplicitInitializerKind - How an implicit base or member initializer should
1498/// initialize its base or member.
1499enum ImplicitInitializerKind {
1500 IIK_Default,
1501 IIK_Copy,
1502 IIK_Move
1503};
1504
Anders Carlssondefefd22010-04-23 02:00:02 +00001505static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001506BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001507 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001508 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001509 bool IsInheritedVirtualBase,
1510 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001511 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001512 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1513 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001514
John McCall60d7b3a2010-08-24 06:29:42 +00001515 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001516
1517 switch (ImplicitInitKind) {
1518 case IIK_Default: {
1519 InitializationKind InitKind
1520 = InitializationKind::CreateDefault(Constructor->getLocation());
1521 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1522 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001523 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001524 break;
1525 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001526
Anders Carlssone5ef7402010-04-23 03:10:23 +00001527 case IIK_Copy: {
1528 ParmVarDecl *Param = Constructor->getParamDecl(0);
1529 QualType ParamType = Param->getType().getNonReferenceType();
1530
1531 Expr *CopyCtorArg =
1532 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001533 Constructor->getLocation(), ParamType,
1534 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001535
Anders Carlssonc7957502010-04-24 22:02:54 +00001536 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001537 QualType ArgTy =
1538 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1539 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001540
1541 CXXCastPath BasePath;
1542 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001543 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001544 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001545 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001546
Anders Carlssone5ef7402010-04-23 03:10:23 +00001547 InitializationKind InitKind
1548 = InitializationKind::CreateDirect(Constructor->getLocation(),
1549 SourceLocation(), SourceLocation());
1550 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1551 &CopyCtorArg, 1);
1552 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001553 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001554 break;
1555 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001556
Anders Carlssone5ef7402010-04-23 03:10:23 +00001557 case IIK_Move:
1558 assert(false && "Unhandled initializer kind!");
1559 }
John McCall9ae2f072010-08-23 23:25:46 +00001560
Douglas Gregor53c374f2010-12-07 00:41:46 +00001561 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001562 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001563 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001564
Anders Carlssondefefd22010-04-23 02:00:02 +00001565 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001566 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1567 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1568 SourceLocation()),
1569 BaseSpec->isVirtual(),
1570 SourceLocation(),
1571 BaseInit.takeAs<Expr>(),
1572 SourceLocation());
1573
Anders Carlssondefefd22010-04-23 02:00:02 +00001574 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001575}
1576
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001577static bool
1578BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001579 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001580 FieldDecl *Field,
1581 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001582 if (Field->isInvalidDecl())
1583 return true;
1584
Chandler Carruthf186b542010-06-29 23:50:44 +00001585 SourceLocation Loc = Constructor->getLocation();
1586
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001587 if (ImplicitInitKind == IIK_Copy) {
1588 ParmVarDecl *Param = Constructor->getParamDecl(0);
1589 QualType ParamType = Param->getType().getNonReferenceType();
1590
1591 Expr *MemberExprBase =
1592 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001593 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001594
1595 // Build a reference to this field within the parameter.
1596 CXXScopeSpec SS;
1597 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1598 Sema::LookupMemberName);
1599 MemberLookup.addDecl(Field, AS_public);
1600 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001601 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001602 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001603 ParamType, Loc,
1604 /*IsArrow=*/false,
1605 SS,
1606 /*FirstQualifierInScope=*/0,
1607 MemberLookup,
1608 /*TemplateArgs=*/0);
1609 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001610 return true;
1611
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001612 // When the field we are copying is an array, create index variables for
1613 // each dimension of the array. We use these index variables to subscript
1614 // the source array, and other clients (e.g., CodeGen) will perform the
1615 // necessary iteration with these index variables.
1616 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1617 QualType BaseType = Field->getType();
1618 QualType SizeType = SemaRef.Context.getSizeType();
1619 while (const ConstantArrayType *Array
1620 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1621 // Create the iteration variable for this array index.
1622 IdentifierInfo *IterationVarName = 0;
1623 {
1624 llvm::SmallString<8> Str;
1625 llvm::raw_svector_ostream OS(Str);
1626 OS << "__i" << IndexVariables.size();
1627 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1628 }
1629 VarDecl *IterationVar
1630 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1631 IterationVarName, SizeType,
1632 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001633 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001634 IndexVariables.push_back(IterationVar);
1635
1636 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001637 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001638 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001639 assert(!IterationVarRef.isInvalid() &&
1640 "Reference to invented variable cannot fail!");
1641
1642 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001643 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001644 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001645 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001646 Loc);
1647 if (CopyCtorArg.isInvalid())
1648 return true;
1649
1650 BaseType = Array->getElementType();
1651 }
1652
1653 // Construct the entity that we will be initializing. For an array, this
1654 // will be first element in the array, which may require several levels
1655 // of array-subscript entities.
1656 llvm::SmallVector<InitializedEntity, 4> Entities;
1657 Entities.reserve(1 + IndexVariables.size());
1658 Entities.push_back(InitializedEntity::InitializeMember(Field));
1659 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1660 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1661 0,
1662 Entities.back()));
1663
1664 // Direct-initialize to use the copy constructor.
1665 InitializationKind InitKind =
1666 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1667
1668 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1669 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1670 &CopyCtorArgE, 1);
1671
John McCall60d7b3a2010-08-24 06:29:42 +00001672 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001673 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001674 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001675 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001676 if (MemberInit.isInvalid())
1677 return true;
1678
1679 CXXMemberInit
1680 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1681 MemberInit.takeAs<Expr>(), Loc,
1682 IndexVariables.data(),
1683 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001684 return false;
1685 }
1686
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001687 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1688
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001689 QualType FieldBaseElementType =
1690 SemaRef.Context.getBaseElementType(Field->getType());
1691
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001692 if (FieldBaseElementType->isRecordType()) {
1693 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001694 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001695 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001696
1697 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001698 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001699 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001700
Douglas Gregor53c374f2010-12-07 00:41:46 +00001701 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001702 if (MemberInit.isInvalid())
1703 return true;
1704
1705 CXXMemberInit =
1706 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001707 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001708 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001709 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001710 return false;
1711 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001712
1713 if (FieldBaseElementType->isReferenceType()) {
1714 SemaRef.Diag(Constructor->getLocation(),
1715 diag::err_uninitialized_member_in_ctor)
1716 << (int)Constructor->isImplicit()
1717 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1718 << 0 << Field->getDeclName();
1719 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1720 return true;
1721 }
1722
1723 if (FieldBaseElementType.isConstQualified()) {
1724 SemaRef.Diag(Constructor->getLocation(),
1725 diag::err_uninitialized_member_in_ctor)
1726 << (int)Constructor->isImplicit()
1727 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1728 << 1 << Field->getDeclName();
1729 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1730 return true;
1731 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001732
1733 // Nothing to initialize.
1734 CXXMemberInit = 0;
1735 return false;
1736}
John McCallf1860e52010-05-20 23:23:51 +00001737
1738namespace {
1739struct BaseAndFieldInfo {
1740 Sema &S;
1741 CXXConstructorDecl *Ctor;
1742 bool AnyErrorsInInits;
1743 ImplicitInitializerKind IIK;
1744 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1745 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1746
1747 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1748 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1749 // FIXME: Handle implicit move constructors.
1750 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1751 IIK = IIK_Copy;
1752 else
1753 IIK = IIK_Default;
1754 }
1755};
1756}
1757
1758static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1759 FieldDecl *Top, FieldDecl *Field) {
1760
Chandler Carruthe861c602010-06-30 02:59:29 +00001761 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001762 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001763 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001764 return false;
1765 }
1766
1767 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1768 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1769 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001770 CXXRecordDecl *FieldClassDecl
1771 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001772
1773 // Even though union members never have non-trivial default
1774 // constructions in C++03, we still build member initializers for aggregate
1775 // record types which can be union members, and C++0x allows non-trivial
1776 // default constructors for union members, so we ensure that only one
1777 // member is initialized for these.
1778 if (FieldClassDecl->isUnion()) {
1779 // First check for an explicit initializer for one field.
1780 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1781 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1782 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001783 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001784
1785 // Once we've initialized a field of an anonymous union, the union
1786 // field in the class is also initialized, so exit immediately.
1787 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001788 } else if ((*FA)->isAnonymousStructOrUnion()) {
1789 if (CollectFieldInitializer(Info, Top, *FA))
1790 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001791 }
1792 }
1793
1794 // Fallthrough and construct a default initializer for the union as
1795 // a whole, which can call its default constructor if such a thing exists
1796 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1797 // behavior going forward with C++0x, when anonymous unions there are
1798 // finalized, we should revisit this.
1799 } else {
1800 // For structs, we simply descend through to initialize all members where
1801 // necessary.
1802 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1803 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1804 if (CollectFieldInitializer(Info, Top, *FA))
1805 return true;
1806 }
1807 }
John McCallf1860e52010-05-20 23:23:51 +00001808 }
1809
1810 // Don't try to build an implicit initializer if there were semantic
1811 // errors in any of the initializers (and therefore we might be
1812 // missing some that the user actually wrote).
1813 if (Info.AnyErrorsInInits)
1814 return false;
1815
1816 CXXBaseOrMemberInitializer *Init = 0;
1817 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1818 return true;
John McCallf1860e52010-05-20 23:23:51 +00001819
Francois Pichet00eb3f92010-12-04 09:14:42 +00001820 if (Init)
1821 Info.AllToInit.push_back(Init);
1822
John McCallf1860e52010-05-20 23:23:51 +00001823 return false;
1824}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001825
Eli Friedman80c30da2009-11-09 19:20:36 +00001826bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001827Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001828 CXXBaseOrMemberInitializer **Initializers,
1829 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001830 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001831 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001832 // Just store the initializers as written, they will be checked during
1833 // instantiation.
1834 if (NumInitializers > 0) {
1835 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1836 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1837 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1838 memcpy(baseOrMemberInitializers, Initializers,
1839 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1840 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1841 }
1842
1843 return false;
1844 }
1845
John McCallf1860e52010-05-20 23:23:51 +00001846 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001847
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001848 // We need to build the initializer AST according to order of construction
1849 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001850 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001851 if (!ClassDecl)
1852 return true;
1853
Eli Friedman80c30da2009-11-09 19:20:36 +00001854 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001856 for (unsigned i = 0; i < NumInitializers; i++) {
1857 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001858
1859 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001860 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001861 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00001862 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001863 }
1864
Anders Carlsson711f34a2010-04-21 19:52:01 +00001865 // Keep track of the direct virtual bases.
1866 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1867 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1868 E = ClassDecl->bases_end(); I != E; ++I) {
1869 if (I->isVirtual())
1870 DirectVBases.insert(I);
1871 }
1872
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001873 // Push virtual bases before others.
1874 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1875 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1876
1877 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001878 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1879 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001880 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001881 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001882 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001883 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001884 VBase, IsInheritedVirtualBase,
1885 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001886 HadError = true;
1887 continue;
1888 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001889
John McCallf1860e52010-05-20 23:23:51 +00001890 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001891 }
1892 }
Mike Stump1eb44332009-09-09 15:08:12 +00001893
John McCallf1860e52010-05-20 23:23:51 +00001894 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001895 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1896 E = ClassDecl->bases_end(); Base != E; ++Base) {
1897 // Virtuals are in the virtual base list and already constructed.
1898 if (Base->isVirtual())
1899 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001901 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001902 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1903 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001904 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001905 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001906 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001907 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001908 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001909 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001910 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001911 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001912
John McCallf1860e52010-05-20 23:23:51 +00001913 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001914 }
1915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
John McCallf1860e52010-05-20 23:23:51 +00001917 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001918 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001919 E = ClassDecl->field_end(); Field != E; ++Field) {
1920 if ((*Field)->getType()->isIncompleteArrayType()) {
1921 assert(ClassDecl->hasFlexibleArrayMember() &&
1922 "Incomplete array type is not valid");
1923 continue;
1924 }
John McCallf1860e52010-05-20 23:23:51 +00001925 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001926 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001927 }
Mike Stump1eb44332009-09-09 15:08:12 +00001928
John McCallf1860e52010-05-20 23:23:51 +00001929 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001930 if (NumInitializers > 0) {
1931 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1932 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1933 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001934 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001935 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001936 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001937
John McCallef027fe2010-03-16 21:39:52 +00001938 // Constructors implicitly reference the base and member
1939 // destructors.
1940 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1941 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001942 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001943
1944 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001945}
1946
Eli Friedman6347f422009-07-21 19:28:10 +00001947static void *GetKeyForTopLevelField(FieldDecl *Field) {
1948 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001949 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001950 if (RT->getDecl()->isAnonymousStructOrUnion())
1951 return static_cast<void *>(RT->getDecl());
1952 }
1953 return static_cast<void *>(Field);
1954}
1955
Anders Carlssonea356fb2010-04-02 05:42:15 +00001956static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1957 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001958}
1959
Anders Carlssonea356fb2010-04-02 05:42:15 +00001960static void *GetKeyForMember(ASTContext &Context,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001961 CXXBaseOrMemberInitializer *Member) {
1962 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001963 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001964
Eli Friedman6347f422009-07-21 19:28:10 +00001965 // For fields injected into the class via declaration of an anonymous union,
1966 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00001967 FieldDecl *Field = Member->getAnyMember();
1968
John McCall3c3ccdb2010-04-10 09:28:51 +00001969 // If the field is a member of an anonymous struct or union, our key
1970 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001971 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001972 if (RD->isAnonymousStructOrUnion()) {
1973 while (true) {
1974 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1975 if (Parent->isAnonymousStructOrUnion())
1976 RD = Parent;
1977 else
1978 break;
1979 }
1980
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001981 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001982 }
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001984 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001985}
1986
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001987static void
1988DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001989 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001990 CXXBaseOrMemberInitializer **Inits,
1991 unsigned NumInits) {
1992 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001993 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001995 // Don't check initializers order unless the warning is enabled at the
1996 // location of at least one initializer.
1997 bool ShouldCheckOrder = false;
1998 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1999 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2000 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2001 Init->getSourceLocation())
2002 != Diagnostic::Ignored) {
2003 ShouldCheckOrder = true;
2004 break;
2005 }
2006 }
2007 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002008 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002009
John McCalld6ca8da2010-04-10 07:37:23 +00002010 // Build the list of bases and members in the order that they'll
2011 // actually be initialized. The explicit initializers should be in
2012 // this same order but may be missing things.
2013 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Anders Carlsson071d6102010-04-02 03:38:04 +00002015 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2016
John McCalld6ca8da2010-04-10 07:37:23 +00002017 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002018 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002019 ClassDecl->vbases_begin(),
2020 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002021 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002022
John McCalld6ca8da2010-04-10 07:37:23 +00002023 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002024 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002025 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002026 if (Base->isVirtual())
2027 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002028 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCalld6ca8da2010-04-10 07:37:23 +00002031 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002032 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2033 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002034 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002035
John McCalld6ca8da2010-04-10 07:37:23 +00002036 unsigned NumIdealInits = IdealInitKeys.size();
2037 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002038
John McCalld6ca8da2010-04-10 07:37:23 +00002039 CXXBaseOrMemberInitializer *PrevInit = 0;
2040 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2041 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002042 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002043
2044 // Scan forward to try to find this initializer in the idealized
2045 // initializers list.
2046 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2047 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002048 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002049
2050 // If we didn't find this initializer, it must be because we
2051 // scanned past it on a previous iteration. That can only
2052 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002053 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002054 Sema::SemaDiagnosticBuilder D =
2055 SemaRef.Diag(PrevInit->getSourceLocation(),
2056 diag::warn_initializer_out_of_order);
2057
Francois Pichet00eb3f92010-12-04 09:14:42 +00002058 if (PrevInit->isAnyMemberInitializer())
2059 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002060 else
2061 D << 1 << PrevInit->getBaseClassInfo()->getType();
2062
Francois Pichet00eb3f92010-12-04 09:14:42 +00002063 if (Init->isAnyMemberInitializer())
2064 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002065 else
2066 D << 1 << Init->getBaseClassInfo()->getType();
2067
2068 // Move back to the initializer's location in the ideal list.
2069 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2070 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002071 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002072
2073 assert(IdealIndex != NumIdealInits &&
2074 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002075 }
John McCalld6ca8da2010-04-10 07:37:23 +00002076
2077 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002078 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002079}
2080
John McCall3c3ccdb2010-04-10 09:28:51 +00002081namespace {
2082bool CheckRedundantInit(Sema &S,
2083 CXXBaseOrMemberInitializer *Init,
2084 CXXBaseOrMemberInitializer *&PrevInit) {
2085 if (!PrevInit) {
2086 PrevInit = Init;
2087 return false;
2088 }
2089
2090 if (FieldDecl *Field = Init->getMember())
2091 S.Diag(Init->getSourceLocation(),
2092 diag::err_multiple_mem_initialization)
2093 << Field->getDeclName()
2094 << Init->getSourceRange();
2095 else {
2096 Type *BaseClass = Init->getBaseClass();
2097 assert(BaseClass && "neither field nor base");
2098 S.Diag(Init->getSourceLocation(),
2099 diag::err_multiple_base_initialization)
2100 << QualType(BaseClass, 0)
2101 << Init->getSourceRange();
2102 }
2103 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2104 << 0 << PrevInit->getSourceRange();
2105
2106 return true;
2107}
2108
2109typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2110typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2111
2112bool CheckRedundantUnionInit(Sema &S,
2113 CXXBaseOrMemberInitializer *Init,
2114 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002115 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002116 RecordDecl *Parent = Field->getParent();
2117 if (!Parent->isAnonymousStructOrUnion())
2118 return false;
2119
2120 NamedDecl *Child = Field;
2121 do {
2122 if (Parent->isUnion()) {
2123 UnionEntry &En = Unions[Parent];
2124 if (En.first && En.first != Child) {
2125 S.Diag(Init->getSourceLocation(),
2126 diag::err_multiple_mem_union_initialization)
2127 << Field->getDeclName()
2128 << Init->getSourceRange();
2129 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2130 << 0 << En.second->getSourceRange();
2131 return true;
2132 } else if (!En.first) {
2133 En.first = Child;
2134 En.second = Init;
2135 }
2136 }
2137
2138 Child = Parent;
2139 Parent = cast<RecordDecl>(Parent->getDeclContext());
2140 } while (Parent->isAnonymousStructOrUnion());
2141
2142 return false;
2143}
2144}
2145
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002146/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002147void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002148 SourceLocation ColonLoc,
2149 MemInitTy **meminits, unsigned NumMemInits,
2150 bool AnyErrors) {
2151 if (!ConstructorDecl)
2152 return;
2153
2154 AdjustDeclIfTemplate(ConstructorDecl);
2155
2156 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002157 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002158
2159 if (!Constructor) {
2160 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2161 return;
2162 }
2163
2164 CXXBaseOrMemberInitializer **MemInits =
2165 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002166
2167 // Mapping for the duplicate initializers check.
2168 // For member initializers, this is keyed with a FieldDecl*.
2169 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002170 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002171
2172 // Mapping for the inconsistent anonymous-union initializers check.
2173 RedundantUnionMap MemberUnions;
2174
Anders Carlssonea356fb2010-04-02 05:42:15 +00002175 bool HadError = false;
2176 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002177 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002178
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002179 // Set the source order index.
2180 Init->setSourceOrder(i);
2181
Francois Pichet00eb3f92010-12-04 09:14:42 +00002182 if (Init->isAnyMemberInitializer()) {
2183 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002184 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2185 CheckRedundantUnionInit(*this, Init, MemberUnions))
2186 HadError = true;
2187 } else {
2188 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2189 if (CheckRedundantInit(*this, Init, Members[Key]))
2190 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002191 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002192 }
2193
Anders Carlssonea356fb2010-04-02 05:42:15 +00002194 if (HadError)
2195 return;
2196
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002197 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002198
2199 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002200}
2201
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002202void
John McCallef027fe2010-03-16 21:39:52 +00002203Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2204 CXXRecordDecl *ClassDecl) {
2205 // Ignore dependent contexts.
2206 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002207 return;
John McCall58e6f342010-03-16 05:22:47 +00002208
2209 // FIXME: all the access-control diagnostics are positioned on the
2210 // field/base declaration. That's probably good; that said, the
2211 // user might reasonably want to know why the destructor is being
2212 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002213
Anders Carlsson9f853df2009-11-17 04:44:12 +00002214 // Non-static data members.
2215 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2216 E = ClassDecl->field_end(); I != E; ++I) {
2217 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002218 if (Field->isInvalidDecl())
2219 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002220 QualType FieldType = Context.getBaseElementType(Field->getType());
2221
2222 const RecordType* RT = FieldType->getAs<RecordType>();
2223 if (!RT)
2224 continue;
2225
2226 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2227 if (FieldClassDecl->hasTrivialDestructor())
2228 continue;
2229
Douglas Gregordb89f282010-07-01 22:47:18 +00002230 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002231 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002232 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002233 << Field->getDeclName()
2234 << FieldType);
2235
John McCallef027fe2010-03-16 21:39:52 +00002236 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002237 }
2238
John McCall58e6f342010-03-16 05:22:47 +00002239 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2240
Anders Carlsson9f853df2009-11-17 04:44:12 +00002241 // Bases.
2242 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2243 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002244 // Bases are always records in a well-formed non-dependent class.
2245 const RecordType *RT = Base->getType()->getAs<RecordType>();
2246
2247 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002248 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002249 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002250
2251 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002252 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002253 if (BaseClassDecl->hasTrivialDestructor())
2254 continue;
John McCall58e6f342010-03-16 05:22:47 +00002255
Douglas Gregordb89f282010-07-01 22:47:18 +00002256 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002257
2258 // FIXME: caret should be on the start of the class name
2259 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002260 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002261 << Base->getType()
2262 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002263
John McCallef027fe2010-03-16 21:39:52 +00002264 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002265 }
2266
2267 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002268 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2269 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002270
2271 // Bases are always records in a well-formed non-dependent class.
2272 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2273
2274 // Ignore direct virtual bases.
2275 if (DirectVirtualBases.count(RT))
2276 continue;
2277
Anders Carlsson9f853df2009-11-17 04:44:12 +00002278 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002279 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002280 if (BaseClassDecl->hasTrivialDestructor())
2281 continue;
John McCall58e6f342010-03-16 05:22:47 +00002282
Douglas Gregordb89f282010-07-01 22:47:18 +00002283 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002284 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002285 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002286 << VBase->getType());
2287
John McCallef027fe2010-03-16 21:39:52 +00002288 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002289 }
2290}
2291
John McCalld226f652010-08-21 09:40:31 +00002292void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002293 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002294 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Mike Stump1eb44332009-09-09 15:08:12 +00002296 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002297 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002298 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002299}
2300
Mike Stump1eb44332009-09-09 15:08:12 +00002301bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002302 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002303 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002304 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002305 else
John McCall94c3b562010-08-18 09:41:07 +00002306 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002307}
2308
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002309bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002310 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002311 if (!getLangOptions().CPlusPlus)
2312 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Anders Carlsson11f21a02009-03-23 19:10:31 +00002314 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002315 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Ted Kremenek6217b802009-07-29 21:53:49 +00002317 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002318 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002319 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002320 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002322 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002323 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002324 }
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Ted Kremenek6217b802009-07-29 21:53:49 +00002326 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002327 if (!RT)
2328 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002329
John McCall86ff3082010-02-04 22:26:26 +00002330 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002331
John McCall94c3b562010-08-18 09:41:07 +00002332 // We can't answer whether something is abstract until it has a
2333 // definition. If it's currently being defined, we'll walk back
2334 // over all the declarations when we have a full definition.
2335 const CXXRecordDecl *Def = RD->getDefinition();
2336 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002337 return false;
2338
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002339 if (!RD->isAbstract())
2340 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002342 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002343 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002344
John McCall94c3b562010-08-18 09:41:07 +00002345 return true;
2346}
2347
2348void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2349 // Check if we've already emitted the list of pure virtual functions
2350 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002351 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002352 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002354 CXXFinalOverriderMap FinalOverriders;
2355 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002357 // Keep a set of seen pure methods so we won't diagnose the same method
2358 // more than once.
2359 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2360
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002361 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2362 MEnd = FinalOverriders.end();
2363 M != MEnd;
2364 ++M) {
2365 for (OverridingMethods::iterator SO = M->second.begin(),
2366 SOEnd = M->second.end();
2367 SO != SOEnd; ++SO) {
2368 // C++ [class.abstract]p4:
2369 // A class is abstract if it contains or inherits at least one
2370 // pure virtual function for which the final overrider is pure
2371 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002373 //
2374 if (SO->second.size() != 1)
2375 continue;
2376
2377 if (!SO->second.front().Method->isPure())
2378 continue;
2379
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002380 if (!SeenPureMethods.insert(SO->second.front().Method))
2381 continue;
2382
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002383 Diag(SO->second.front().Method->getLocation(),
2384 diag::note_pure_virtual_function)
2385 << SO->second.front().Method->getDeclName();
2386 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002387 }
2388
2389 if (!PureVirtualClassDiagSet)
2390 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2391 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002392}
2393
Anders Carlsson8211eff2009-03-24 01:19:16 +00002394namespace {
John McCall94c3b562010-08-18 09:41:07 +00002395struct AbstractUsageInfo {
2396 Sema &S;
2397 CXXRecordDecl *Record;
2398 CanQualType AbstractType;
2399 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002400
John McCall94c3b562010-08-18 09:41:07 +00002401 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2402 : S(S), Record(Record),
2403 AbstractType(S.Context.getCanonicalType(
2404 S.Context.getTypeDeclType(Record))),
2405 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002406
John McCall94c3b562010-08-18 09:41:07 +00002407 void DiagnoseAbstractType() {
2408 if (Invalid) return;
2409 S.DiagnoseAbstractType(Record);
2410 Invalid = true;
2411 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002412
John McCall94c3b562010-08-18 09:41:07 +00002413 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2414};
2415
2416struct CheckAbstractUsage {
2417 AbstractUsageInfo &Info;
2418 const NamedDecl *Ctx;
2419
2420 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2421 : Info(Info), Ctx(Ctx) {}
2422
2423 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2424 switch (TL.getTypeLocClass()) {
2425#define ABSTRACT_TYPELOC(CLASS, PARENT)
2426#define TYPELOC(CLASS, PARENT) \
2427 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2428#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002429 }
John McCall94c3b562010-08-18 09:41:07 +00002430 }
Mike Stump1eb44332009-09-09 15:08:12 +00002431
John McCall94c3b562010-08-18 09:41:07 +00002432 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2433 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2434 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2435 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2436 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002437 }
John McCall94c3b562010-08-18 09:41:07 +00002438 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002439
John McCall94c3b562010-08-18 09:41:07 +00002440 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2441 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
John McCall94c3b562010-08-18 09:41:07 +00002444 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2445 // Visit the type parameters from a permissive context.
2446 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2447 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2448 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2449 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2450 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2451 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002452 }
John McCall94c3b562010-08-18 09:41:07 +00002453 }
Mike Stump1eb44332009-09-09 15:08:12 +00002454
John McCall94c3b562010-08-18 09:41:07 +00002455 // Visit pointee types from a permissive context.
2456#define CheckPolymorphic(Type) \
2457 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2458 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2459 }
2460 CheckPolymorphic(PointerTypeLoc)
2461 CheckPolymorphic(ReferenceTypeLoc)
2462 CheckPolymorphic(MemberPointerTypeLoc)
2463 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002464
John McCall94c3b562010-08-18 09:41:07 +00002465 /// Handle all the types we haven't given a more specific
2466 /// implementation for above.
2467 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2468 // Every other kind of type that we haven't called out already
2469 // that has an inner type is either (1) sugar or (2) contains that
2470 // inner type in some way as a subobject.
2471 if (TypeLoc Next = TL.getNextTypeLoc())
2472 return Visit(Next, Sel);
2473
2474 // If there's no inner type and we're in a permissive context,
2475 // don't diagnose.
2476 if (Sel == Sema::AbstractNone) return;
2477
2478 // Check whether the type matches the abstract type.
2479 QualType T = TL.getType();
2480 if (T->isArrayType()) {
2481 Sel = Sema::AbstractArrayType;
2482 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002483 }
John McCall94c3b562010-08-18 09:41:07 +00002484 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2485 if (CT != Info.AbstractType) return;
2486
2487 // It matched; do some magic.
2488 if (Sel == Sema::AbstractArrayType) {
2489 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2490 << T << TL.getSourceRange();
2491 } else {
2492 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2493 << Sel << T << TL.getSourceRange();
2494 }
2495 Info.DiagnoseAbstractType();
2496 }
2497};
2498
2499void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2500 Sema::AbstractDiagSelID Sel) {
2501 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2502}
2503
2504}
2505
2506/// Check for invalid uses of an abstract type in a method declaration.
2507static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2508 CXXMethodDecl *MD) {
2509 // No need to do the check on definitions, which require that
2510 // the return/param types be complete.
2511 if (MD->isThisDeclarationADefinition())
2512 return;
2513
2514 // For safety's sake, just ignore it if we don't have type source
2515 // information. This should never happen for non-implicit methods,
2516 // but...
2517 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2518 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2519}
2520
2521/// Check for invalid uses of an abstract type within a class definition.
2522static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2523 CXXRecordDecl *RD) {
2524 for (CXXRecordDecl::decl_iterator
2525 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2526 Decl *D = *I;
2527 if (D->isImplicit()) continue;
2528
2529 // Methods and method templates.
2530 if (isa<CXXMethodDecl>(D)) {
2531 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2532 } else if (isa<FunctionTemplateDecl>(D)) {
2533 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2534 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2535
2536 // Fields and static variables.
2537 } else if (isa<FieldDecl>(D)) {
2538 FieldDecl *FD = cast<FieldDecl>(D);
2539 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2540 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2541 } else if (isa<VarDecl>(D)) {
2542 VarDecl *VD = cast<VarDecl>(D);
2543 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2544 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2545
2546 // Nested classes and class templates.
2547 } else if (isa<CXXRecordDecl>(D)) {
2548 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2549 } else if (isa<ClassTemplateDecl>(D)) {
2550 CheckAbstractClassUsage(Info,
2551 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2552 }
2553 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002554}
2555
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002556/// \brief Perform semantic checks on a class definition that has been
2557/// completing, introducing implicitly-declared members, checking for
2558/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002559void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002560 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002561 return;
2562
John McCall94c3b562010-08-18 09:41:07 +00002563 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2564 AbstractUsageInfo Info(*this, Record);
2565 CheckAbstractClassUsage(Info, Record);
2566 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002567
2568 // If this is not an aggregate type and has no user-declared constructor,
2569 // complain about any non-static data members of reference or const scalar
2570 // type, since they will never get initializers.
2571 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2572 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2573 bool Complained = false;
2574 for (RecordDecl::field_iterator F = Record->field_begin(),
2575 FEnd = Record->field_end();
2576 F != FEnd; ++F) {
2577 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002578 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002579 if (!Complained) {
2580 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2581 << Record->getTagKind() << Record;
2582 Complained = true;
2583 }
2584
2585 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2586 << F->getType()->isReferenceType()
2587 << F->getDeclName();
2588 }
2589 }
2590 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002591
2592 if (Record->isDynamicClass())
2593 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002594
2595 if (Record->getIdentifier()) {
2596 // C++ [class.mem]p13:
2597 // If T is the name of a class, then each of the following shall have a
2598 // name different from T:
2599 // - every member of every anonymous union that is a member of class T.
2600 //
2601 // C++ [class.mem]p14:
2602 // In addition, if class T has a user-declared constructor (12.1), every
2603 // non-static data member of class T shall have a name different from T.
2604 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002605 R.first != R.second; ++R.first) {
2606 NamedDecl *D = *R.first;
2607 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2608 isa<IndirectFieldDecl>(D)) {
2609 Diag(D->getLocation(), diag::err_member_name_of_class)
2610 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002611 break;
2612 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002613 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002614 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002615}
2616
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002617void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002618 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002619 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002620 SourceLocation RBrac,
2621 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002622 if (!TagDecl)
2623 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor42af25f2009-05-11 19:58:34 +00002625 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002626
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002627 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002628 // strict aliasing violation!
2629 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002630 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002631
Douglas Gregor23c94db2010-07-02 17:43:08 +00002632 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002633 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002634}
2635
Douglas Gregord92ec472010-07-01 05:10:53 +00002636namespace {
2637 /// \brief Helper class that collects exception specifications for
2638 /// implicitly-declared special member functions.
2639 class ImplicitExceptionSpecification {
2640 ASTContext &Context;
2641 bool AllowsAllExceptions;
2642 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2643 llvm::SmallVector<QualType, 4> Exceptions;
2644
2645 public:
2646 explicit ImplicitExceptionSpecification(ASTContext &Context)
2647 : Context(Context), AllowsAllExceptions(false) { }
2648
2649 /// \brief Whether the special member function should have any
2650 /// exception specification at all.
2651 bool hasExceptionSpecification() const {
2652 return !AllowsAllExceptions;
2653 }
2654
2655 /// \brief Whether the special member function should have a
2656 /// throw(...) exception specification (a Microsoft extension).
2657 bool hasAnyExceptionSpecification() const {
2658 return false;
2659 }
2660
2661 /// \brief The number of exceptions in the exception specification.
2662 unsigned size() const { return Exceptions.size(); }
2663
2664 /// \brief The set of exceptions in the exception specification.
2665 const QualType *data() const { return Exceptions.data(); }
2666
2667 /// \brief Note that
2668 void CalledDecl(CXXMethodDecl *Method) {
2669 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002670 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002671 return;
2672
2673 const FunctionProtoType *Proto
2674 = Method->getType()->getAs<FunctionProtoType>();
2675
2676 // If this function can throw any exceptions, make a note of that.
2677 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2678 AllowsAllExceptions = true;
2679 ExceptionsSeen.clear();
2680 Exceptions.clear();
2681 return;
2682 }
2683
2684 // Record the exceptions in this function's exception specification.
2685 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2686 EEnd = Proto->exception_end();
2687 E != EEnd; ++E)
2688 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2689 Exceptions.push_back(*E);
2690 }
2691 };
2692}
2693
2694
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002695/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2696/// special functions, such as the default constructor, copy
2697/// constructor, or destructor, to the given C++ class (C++
2698/// [special]p1). This routine can only be executed just before the
2699/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002700void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002701 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002702 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002703
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002704 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002705 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002706
Douglas Gregora376d102010-07-02 21:50:04 +00002707 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2708 ++ASTContext::NumImplicitCopyAssignmentOperators;
2709
2710 // If we have a dynamic class, then the copy assignment operator may be
2711 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2712 // it shows up in the right place in the vtable and that we diagnose
2713 // problems with the implicit exception specification.
2714 if (ClassDecl->isDynamicClass())
2715 DeclareImplicitCopyAssignment(ClassDecl);
2716 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002717
Douglas Gregor4923aa22010-07-02 20:37:36 +00002718 if (!ClassDecl->hasUserDeclaredDestructor()) {
2719 ++ASTContext::NumImplicitDestructors;
2720
2721 // If we have a dynamic class, then the destructor may be virtual, so we
2722 // have to declare the destructor immediately. This ensures that, e.g., it
2723 // shows up in the right place in the vtable and that we diagnose problems
2724 // with the implicit exception specification.
2725 if (ClassDecl->isDynamicClass())
2726 DeclareImplicitDestructor(ClassDecl);
2727 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002728}
2729
John McCalld226f652010-08-21 09:40:31 +00002730void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002731 if (!D)
2732 return;
2733
2734 TemplateParameterList *Params = 0;
2735 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2736 Params = Template->getTemplateParameters();
2737 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2738 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2739 Params = PartialSpec->getTemplateParameters();
2740 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002741 return;
2742
Douglas Gregor6569d682009-05-27 23:11:45 +00002743 for (TemplateParameterList::iterator Param = Params->begin(),
2744 ParamEnd = Params->end();
2745 Param != ParamEnd; ++Param) {
2746 NamedDecl *Named = cast<NamedDecl>(*Param);
2747 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002748 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002749 IdResolver.AddDecl(Named);
2750 }
2751 }
2752}
2753
John McCalld226f652010-08-21 09:40:31 +00002754void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002755 if (!RecordD) return;
2756 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002757 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002758 PushDeclContext(S, Record);
2759}
2760
John McCalld226f652010-08-21 09:40:31 +00002761void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002762 if (!RecordD) return;
2763 PopDeclContext();
2764}
2765
Douglas Gregor72b505b2008-12-16 21:30:33 +00002766/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2767/// parsing a top-level (non-nested) C++ class, and we are now
2768/// parsing those parts of the given Method declaration that could
2769/// not be parsed earlier (C++ [class.mem]p2), such as default
2770/// arguments. This action should enter the scope of the given
2771/// Method declaration as if we had just parsed the qualified method
2772/// name. However, it should not bring the parameters into scope;
2773/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002774void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002775}
2776
2777/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2778/// C++ method declaration. We're (re-)introducing the given
2779/// function parameter into scope for use in parsing later parts of
2780/// the method declaration. For example, we could see an
2781/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002782void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002783 if (!ParamD)
2784 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002785
John McCalld226f652010-08-21 09:40:31 +00002786 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002787
2788 // If this parameter has an unparsed default argument, clear it out
2789 // to make way for the parsed default argument.
2790 if (Param->hasUnparsedDefaultArg())
2791 Param->setDefaultArg(0);
2792
John McCalld226f652010-08-21 09:40:31 +00002793 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002794 if (Param->getDeclName())
2795 IdResolver.AddDecl(Param);
2796}
2797
2798/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2799/// processing the delayed method declaration for Method. The method
2800/// declaration is now considered finished. There may be a separate
2801/// ActOnStartOfFunctionDef action later (not necessarily
2802/// immediately!) for this method, if it was also defined inside the
2803/// class body.
John McCalld226f652010-08-21 09:40:31 +00002804void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002805 if (!MethodD)
2806 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002808 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002809
John McCalld226f652010-08-21 09:40:31 +00002810 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002811
2812 // Now that we have our default arguments, check the constructor
2813 // again. It could produce additional diagnostics or affect whether
2814 // the class has implicitly-declared destructors, among other
2815 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002816 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2817 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002818
2819 // Check the default arguments, which we may have added.
2820 if (!Method->isInvalidDecl())
2821 CheckCXXDefaultArguments(Method);
2822}
2823
Douglas Gregor42a552f2008-11-05 20:51:48 +00002824/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002825/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002826/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002827/// emit diagnostics and set the invalid bit to true. In any case, the type
2828/// will be updated to reflect a well-formed type for the constructor and
2829/// returned.
2830QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002831 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002832 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002833
2834 // C++ [class.ctor]p3:
2835 // A constructor shall not be virtual (10.3) or static (9.4). A
2836 // constructor can be invoked for a const, volatile or const
2837 // volatile object. A constructor shall not be declared const,
2838 // volatile, or const volatile (9.3.2).
2839 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002840 if (!D.isInvalidType())
2841 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2842 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2843 << SourceRange(D.getIdentifierLoc());
2844 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002845 }
John McCalld931b082010-08-26 03:08:43 +00002846 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002847 if (!D.isInvalidType())
2848 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2849 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2850 << SourceRange(D.getIdentifierLoc());
2851 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002852 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002853 }
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002855 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00002856 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002857 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002858 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2859 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002860 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002861 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2862 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002863 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002864 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2865 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00002866 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002867 }
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Douglas Gregor42a552f2008-11-05 20:51:48 +00002869 // Rebuild the function type "R" without any type qualifiers (in
2870 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002871 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002872 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00002873 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2874 return R;
2875
2876 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2877 EPI.TypeQuals = 0;
2878
Chris Lattner65401802009-04-25 08:28:21 +00002879 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00002880 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002881}
2882
Douglas Gregor72b505b2008-12-16 21:30:33 +00002883/// CheckConstructor - Checks a fully-formed constructor for
2884/// well-formedness, issuing any diagnostics required. Returns true if
2885/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002886void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002887 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002888 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2889 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002890 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002891
2892 // C++ [class.copy]p3:
2893 // A declaration of a constructor for a class X is ill-formed if
2894 // its first parameter is of type (optionally cv-qualified) X and
2895 // either there are no other parameters or else all other
2896 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002897 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002898 ((Constructor->getNumParams() == 1) ||
2899 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002900 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2901 Constructor->getTemplateSpecializationKind()
2902 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002903 QualType ParamType = Constructor->getParamDecl(0)->getType();
2904 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2905 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002906 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002907 const char *ConstRef
2908 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2909 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002910 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002911 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002912
2913 // FIXME: Rather that making the constructor invalid, we should endeavor
2914 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002915 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002916 }
2917 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002918}
2919
John McCall15442822010-08-04 01:04:25 +00002920/// CheckDestructor - Checks a fully-formed destructor definition for
2921/// well-formedness, issuing any diagnostics required. Returns true
2922/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002923bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002924 CXXRecordDecl *RD = Destructor->getParent();
2925
2926 if (Destructor->isVirtual()) {
2927 SourceLocation Loc;
2928
2929 if (!Destructor->isImplicit())
2930 Loc = Destructor->getLocation();
2931 else
2932 Loc = RD->getLocation();
2933
2934 // If we have a virtual destructor, look up the deallocation function
2935 FunctionDecl *OperatorDelete = 0;
2936 DeclarationName Name =
2937 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002938 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002939 return true;
John McCall5efd91a2010-07-03 18:33:00 +00002940
2941 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00002942
2943 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002944 }
Anders Carlsson37909802009-11-30 21:24:50 +00002945
2946 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002947}
2948
Mike Stump1eb44332009-09-09 15:08:12 +00002949static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002950FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2951 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2952 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00002953 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002954}
2955
Douglas Gregor42a552f2008-11-05 20:51:48 +00002956/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2957/// the well-formednes of the destructor declarator @p D with type @p
2958/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002959/// emit diagnostics and set the declarator to invalid. Even if this happens,
2960/// will be updated to reflect a well-formed type for the destructor and
2961/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00002962QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002963 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002964 // C++ [class.dtor]p1:
2965 // [...] A typedef-name that names a class is a class-name
2966 // (7.1.3); however, a typedef-name that names a class shall not
2967 // be used as the identifier in the declarator for a destructor
2968 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002969 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00002970 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00002971 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002972 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002973
2974 // C++ [class.dtor]p2:
2975 // A destructor is used to destroy objects of its class type. A
2976 // destructor takes no parameters, and no return type can be
2977 // specified for it (not even void). The address of a destructor
2978 // shall not be taken. A destructor shall not be static. A
2979 // destructor can be invoked for a const, volatile or const
2980 // volatile object. A destructor shall not be declared const,
2981 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00002982 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002983 if (!D.isInvalidType())
2984 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2985 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00002986 << SourceRange(D.getIdentifierLoc())
2987 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2988
John McCalld931b082010-08-26 03:08:43 +00002989 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002990 }
Chris Lattner65401802009-04-25 08:28:21 +00002991 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002992 // Destructors don't have return types, but the parser will
2993 // happily parse something like:
2994 //
2995 // class X {
2996 // float ~X();
2997 // };
2998 //
2999 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003000 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3001 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3002 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003003 }
Mike Stump1eb44332009-09-09 15:08:12 +00003004
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003005 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003006 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003007 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003008 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3009 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003010 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003011 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3012 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003013 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003014 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3015 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003016 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003017 }
3018
3019 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003020 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003021 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3022
3023 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003024 FTI.freeArgs();
3025 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003026 }
3027
Mike Stump1eb44332009-09-09 15:08:12 +00003028 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003029 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003030 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003031 D.setInvalidType();
3032 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003033
3034 // Rebuild the function type "R" without any type qualifiers or
3035 // parameters (in case any of the errors above fired) and with
3036 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003037 // types.
John McCalle23cf432010-12-14 08:05:40 +00003038 if (!D.isInvalidType())
3039 return R;
3040
Douglas Gregord92ec472010-07-01 05:10:53 +00003041 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003042 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3043 EPI.Variadic = false;
3044 EPI.TypeQuals = 0;
3045 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003046}
3047
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003048/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3049/// well-formednes of the conversion function declarator @p D with
3050/// type @p R. If there are any errors in the declarator, this routine
3051/// will emit diagnostics and return true. Otherwise, it will return
3052/// false. Either way, the type @p R will be updated to reflect a
3053/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003054void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003055 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003056 // C++ [class.conv.fct]p1:
3057 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003058 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003059 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003060 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003061 if (!D.isInvalidType())
3062 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3063 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3064 << SourceRange(D.getIdentifierLoc());
3065 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003066 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003067 }
John McCalla3f81372010-04-13 00:04:31 +00003068
3069 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3070
Chris Lattner6e475012009-04-25 08:35:12 +00003071 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003072 // Conversion functions don't have return types, but the parser will
3073 // happily parse something like:
3074 //
3075 // class X {
3076 // float operator bool();
3077 // };
3078 //
3079 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003080 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3081 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3082 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003083 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003084 }
3085
John McCalla3f81372010-04-13 00:04:31 +00003086 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3087
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003088 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003089 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003090 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3091
3092 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003093 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003094 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003095 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003096 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003097 D.setInvalidType();
3098 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003099
John McCalla3f81372010-04-13 00:04:31 +00003100 // Diagnose "&operator bool()" and other such nonsense. This
3101 // is actually a gcc extension which we don't support.
3102 if (Proto->getResultType() != ConvType) {
3103 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3104 << Proto->getResultType();
3105 D.setInvalidType();
3106 ConvType = Proto->getResultType();
3107 }
3108
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003109 // C++ [class.conv.fct]p4:
3110 // The conversion-type-id shall not represent a function type nor
3111 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003112 if (ConvType->isArrayType()) {
3113 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3114 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003115 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003116 } else if (ConvType->isFunctionType()) {
3117 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3118 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003119 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003120 }
3121
3122 // Rebuild the function type "R" without any parameters (in case any
3123 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003124 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003125 if (D.isInvalidType())
3126 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003127
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003128 // C++0x explicit conversion operators.
3129 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003130 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003131 diag::warn_explicit_conversion_functions)
3132 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003133}
3134
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003135/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3136/// the declaration of the given C++ conversion function. This routine
3137/// is responsible for recording the conversion function in the C++
3138/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003139Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003140 assert(Conversion && "Expected to receive a conversion function declaration");
3141
Douglas Gregor9d350972008-12-12 08:25:50 +00003142 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003143
3144 // Make sure we aren't redeclaring the conversion function.
3145 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003146
3147 // C++ [class.conv.fct]p1:
3148 // [...] A conversion function is never used to convert a
3149 // (possibly cv-qualified) object to the (possibly cv-qualified)
3150 // same object type (or a reference to it), to a (possibly
3151 // cv-qualified) base class of that type (or a reference to it),
3152 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003153 // FIXME: Suppress this warning if the conversion function ends up being a
3154 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003155 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003156 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003157 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003158 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003159 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3160 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003161 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003162 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003163 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3164 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003165 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003166 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003167 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003168 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003169 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003170 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003171 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003172 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003173 }
3174
Douglas Gregore80622f2010-09-29 04:25:11 +00003175 if (FunctionTemplateDecl *ConversionTemplate
3176 = Conversion->getDescribedFunctionTemplate())
3177 return ConversionTemplate;
3178
John McCalld226f652010-08-21 09:40:31 +00003179 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003180}
3181
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003182//===----------------------------------------------------------------------===//
3183// Namespace Handling
3184//===----------------------------------------------------------------------===//
3185
John McCallea318642010-08-26 09:15:37 +00003186
3187
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003188/// ActOnStartNamespaceDef - This is called at the start of a namespace
3189/// definition.
John McCalld226f652010-08-21 09:40:31 +00003190Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003191 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003192 SourceLocation IdentLoc,
3193 IdentifierInfo *II,
3194 SourceLocation LBrace,
3195 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003196 // anonymous namespace starts at its left brace
3197 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3198 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003199 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003200 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003201
3202 Scope *DeclRegionScope = NamespcScope->getParent();
3203
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003204 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3205
John McCall90f14502010-12-10 02:59:44 +00003206 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3207 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003208
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003209 if (II) {
3210 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003211 // The identifier in an original-namespace-definition shall not
3212 // have been previously defined in the declarative region in
3213 // which the original-namespace-definition appears. The
3214 // identifier in an original-namespace-definition is the name of
3215 // the namespace. Subsequently in that declarative region, it is
3216 // treated as an original-namespace-name.
3217 //
3218 // Since namespace names are unique in their scope, and we don't
3219 // look through using directives, just
3220 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3221 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Douglas Gregor44b43212008-12-11 16:49:14 +00003223 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3224 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003225 if (Namespc->isInline() != OrigNS->isInline()) {
3226 // inline-ness must match
3227 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3228 << Namespc->isInline();
3229 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3230 Namespc->setInvalidDecl();
3231 // Recover by ignoring the new namespace's inline status.
3232 Namespc->setInline(OrigNS->isInline());
3233 }
3234
Douglas Gregor44b43212008-12-11 16:49:14 +00003235 // Attach this namespace decl to the chain of extended namespace
3236 // definitions.
3237 OrigNS->setNextNamespace(Namespc);
3238 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003239
Mike Stump1eb44332009-09-09 15:08:12 +00003240 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003241 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003242 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003243 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003244 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003245 } else if (PrevDecl) {
3246 // This is an invalid name redefinition.
3247 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3248 << Namespc->getDeclName();
3249 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3250 Namespc->setInvalidDecl();
3251 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003252 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003253 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003254 // This is the first "real" definition of the namespace "std", so update
3255 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003256 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003257 // We had already defined a dummy namespace "std". Link this new
3258 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003259 StdNS->setNextNamespace(Namespc);
3260 StdNS->setLocation(IdentLoc);
3261 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003262 }
3263
3264 // Make our StdNamespace cache point at the first real definition of the
3265 // "std" namespace.
3266 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003267 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003268
3269 PushOnScopeChains(Namespc, DeclRegionScope);
3270 } else {
John McCall9aeed322009-10-01 00:25:31 +00003271 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003272 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003273
3274 // Link the anonymous namespace into its parent.
3275 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003276 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003277 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3278 PrevDecl = TU->getAnonymousNamespace();
3279 TU->setAnonymousNamespace(Namespc);
3280 } else {
3281 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3282 PrevDecl = ND->getAnonymousNamespace();
3283 ND->setAnonymousNamespace(Namespc);
3284 }
3285
3286 // Link the anonymous namespace with its previous declaration.
3287 if (PrevDecl) {
3288 assert(PrevDecl->isAnonymousNamespace());
3289 assert(!PrevDecl->getNextNamespace());
3290 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3291 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003292
3293 if (Namespc->isInline() != PrevDecl->isInline()) {
3294 // inline-ness must match
3295 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3296 << Namespc->isInline();
3297 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3298 Namespc->setInvalidDecl();
3299 // Recover by ignoring the new namespace's inline status.
3300 Namespc->setInline(PrevDecl->isInline());
3301 }
John McCall5fdd7642009-12-16 02:06:49 +00003302 }
John McCall9aeed322009-10-01 00:25:31 +00003303
Douglas Gregora4181472010-03-24 00:46:35 +00003304 CurContext->addDecl(Namespc);
3305
John McCall9aeed322009-10-01 00:25:31 +00003306 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3307 // behaves as if it were replaced by
3308 // namespace unique { /* empty body */ }
3309 // using namespace unique;
3310 // namespace unique { namespace-body }
3311 // where all occurrences of 'unique' in a translation unit are
3312 // replaced by the same identifier and this identifier differs
3313 // from all other identifiers in the entire program.
3314
3315 // We just create the namespace with an empty name and then add an
3316 // implicit using declaration, just like the standard suggests.
3317 //
3318 // CodeGen enforces the "universally unique" aspect by giving all
3319 // declarations semantically contained within an anonymous
3320 // namespace internal linkage.
3321
John McCall5fdd7642009-12-16 02:06:49 +00003322 if (!PrevDecl) {
3323 UsingDirectiveDecl* UD
3324 = UsingDirectiveDecl::Create(Context, CurContext,
3325 /* 'using' */ LBrace,
3326 /* 'namespace' */ SourceLocation(),
3327 /* qualifier */ SourceRange(),
3328 /* NNS */ NULL,
3329 /* identifier */ SourceLocation(),
3330 Namespc,
3331 /* Ancestor */ CurContext);
3332 UD->setImplicit();
3333 CurContext->addDecl(UD);
3334 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003335 }
3336
3337 // Although we could have an invalid decl (i.e. the namespace name is a
3338 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003339 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3340 // for the namespace has the declarations that showed up in that particular
3341 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003342 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003343 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003344}
3345
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003346/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3347/// is a namespace alias, returns the namespace it points to.
3348static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3349 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3350 return AD->getNamespace();
3351 return dyn_cast_or_null<NamespaceDecl>(D);
3352}
3353
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003354/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3355/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003356void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003357 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3358 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3359 Namespc->setRBracLoc(RBrace);
3360 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003361 if (Namespc->hasAttr<VisibilityAttr>())
3362 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003363}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003364
John McCall384aff82010-08-25 07:42:41 +00003365CXXRecordDecl *Sema::getStdBadAlloc() const {
3366 return cast_or_null<CXXRecordDecl>(
3367 StdBadAlloc.get(Context.getExternalSource()));
3368}
3369
3370NamespaceDecl *Sema::getStdNamespace() const {
3371 return cast_or_null<NamespaceDecl>(
3372 StdNamespace.get(Context.getExternalSource()));
3373}
3374
Douglas Gregor66992202010-06-29 17:53:46 +00003375/// \brief Retrieve the special "std" namespace, which may require us to
3376/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003377NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003378 if (!StdNamespace) {
3379 // The "std" namespace has not yet been defined, so build one implicitly.
3380 StdNamespace = NamespaceDecl::Create(Context,
3381 Context.getTranslationUnitDecl(),
3382 SourceLocation(),
3383 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003384 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003385 }
3386
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003387 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003388}
3389
John McCalld226f652010-08-21 09:40:31 +00003390Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003391 SourceLocation UsingLoc,
3392 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003393 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003394 SourceLocation IdentLoc,
3395 IdentifierInfo *NamespcName,
3396 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003397 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3398 assert(NamespcName && "Invalid NamespcName.");
3399 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003400
3401 // This can only happen along a recovery path.
3402 while (S->getFlags() & Scope::TemplateParamScope)
3403 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003404 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003405
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003406 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003407 NestedNameSpecifier *Qualifier = 0;
3408 if (SS.isSet())
3409 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3410
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003411 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003412 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3413 LookupParsedName(R, S, &SS);
3414 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003415 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003416
Douglas Gregor66992202010-06-29 17:53:46 +00003417 if (R.empty()) {
3418 // Allow "using namespace std;" or "using namespace ::std;" even if
3419 // "std" hasn't been defined yet, for GCC compatibility.
3420 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3421 NamespcName->isStr("std")) {
3422 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003423 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003424 R.resolveKind();
3425 }
3426 // Otherwise, attempt typo correction.
3427 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3428 CTC_NoKeywords, 0)) {
3429 if (R.getAsSingle<NamespaceDecl>() ||
3430 R.getAsSingle<NamespaceAliasDecl>()) {
3431 if (DeclContext *DC = computeDeclContext(SS, false))
3432 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3433 << NamespcName << DC << Corrected << SS.getRange()
3434 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3435 else
3436 Diag(IdentLoc, diag::err_using_directive_suggest)
3437 << NamespcName << Corrected
3438 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3439 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3440 << Corrected;
3441
3442 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003443 } else {
3444 R.clear();
3445 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003446 }
3447 }
3448 }
3449
John McCallf36e02d2009-10-09 21:13:30 +00003450 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003451 NamedDecl *Named = R.getFoundDecl();
3452 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3453 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003454 // C++ [namespace.udir]p1:
3455 // A using-directive specifies that the names in the nominated
3456 // namespace can be used in the scope in which the
3457 // using-directive appears after the using-directive. During
3458 // unqualified name lookup (3.4.1), the names appear as if they
3459 // were declared in the nearest enclosing namespace which
3460 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003461 // namespace. [Note: in this context, "contains" means "contains
3462 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003463
3464 // Find enclosing context containing both using-directive and
3465 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003466 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003467 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3468 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3469 CommonAncestor = CommonAncestor->getParent();
3470
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003471 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003472 SS.getRange(),
3473 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003474 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003475 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003476 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003477 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003478 }
3479
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003480 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003481 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003482}
3483
3484void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3485 // If scope has associated entity, then using directive is at namespace
3486 // or translation unit scope. We add UsingDirectiveDecls, into
3487 // it's lookup structure.
3488 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003489 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003490 else
3491 // Otherwise it is block-sope. using-directives will affect lookup
3492 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003493 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003494}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003495
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003496
John McCalld226f652010-08-21 09:40:31 +00003497Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003498 AccessSpecifier AS,
3499 bool HasUsingKeyword,
3500 SourceLocation UsingLoc,
3501 CXXScopeSpec &SS,
3502 UnqualifiedId &Name,
3503 AttributeList *AttrList,
3504 bool IsTypeName,
3505 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003506 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Douglas Gregor12c118a2009-11-04 16:30:06 +00003508 switch (Name.getKind()) {
3509 case UnqualifiedId::IK_Identifier:
3510 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003511 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003512 case UnqualifiedId::IK_ConversionFunctionId:
3513 break;
3514
3515 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003516 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003517 // C++0x inherited constructors.
3518 if (getLangOptions().CPlusPlus0x) break;
3519
Douglas Gregor12c118a2009-11-04 16:30:06 +00003520 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3521 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003522 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003523
3524 case UnqualifiedId::IK_DestructorName:
3525 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3526 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003527 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003528
3529 case UnqualifiedId::IK_TemplateId:
3530 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3531 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003532 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003533 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003534
3535 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3536 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003537 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003538 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003539
John McCall60fa3cf2009-12-11 02:10:03 +00003540 // Warn about using declarations.
3541 // TODO: store that the declaration was written without 'using' and
3542 // talk about access decls instead of using decls in the
3543 // diagnostics.
3544 if (!HasUsingKeyword) {
3545 UsingLoc = Name.getSourceRange().getBegin();
3546
3547 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003548 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003549 }
3550
Douglas Gregor56c04582010-12-16 00:46:58 +00003551 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3552 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3553 return 0;
3554
John McCall9488ea12009-11-17 05:59:44 +00003555 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003556 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003557 /* IsInstantiation */ false,
3558 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003559 if (UD)
3560 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003561
John McCalld226f652010-08-21 09:40:31 +00003562 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003563}
3564
Douglas Gregor09acc982010-07-07 23:08:52 +00003565/// \brief Determine whether a using declaration considers the given
3566/// declarations as "equivalent", e.g., if they are redeclarations of
3567/// the same entity or are both typedefs of the same type.
3568static bool
3569IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3570 bool &SuppressRedeclaration) {
3571 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3572 SuppressRedeclaration = false;
3573 return true;
3574 }
3575
3576 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3577 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3578 SuppressRedeclaration = true;
3579 return Context.hasSameType(TD1->getUnderlyingType(),
3580 TD2->getUnderlyingType());
3581 }
3582
3583 return false;
3584}
3585
3586
John McCall9f54ad42009-12-10 09:41:52 +00003587/// Determines whether to create a using shadow decl for a particular
3588/// decl, given the set of decls existing prior to this using lookup.
3589bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3590 const LookupResult &Previous) {
3591 // Diagnose finding a decl which is not from a base class of the
3592 // current class. We do this now because there are cases where this
3593 // function will silently decide not to build a shadow decl, which
3594 // will pre-empt further diagnostics.
3595 //
3596 // We don't need to do this in C++0x because we do the check once on
3597 // the qualifier.
3598 //
3599 // FIXME: diagnose the following if we care enough:
3600 // struct A { int foo; };
3601 // struct B : A { using A::foo; };
3602 // template <class T> struct C : A {};
3603 // template <class T> struct D : C<T> { using B::foo; } // <---
3604 // This is invalid (during instantiation) in C++03 because B::foo
3605 // resolves to the using decl in B, which is not a base class of D<T>.
3606 // We can't diagnose it immediately because C<T> is an unknown
3607 // specialization. The UsingShadowDecl in D<T> then points directly
3608 // to A::foo, which will look well-formed when we instantiate.
3609 // The right solution is to not collapse the shadow-decl chain.
3610 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3611 DeclContext *OrigDC = Orig->getDeclContext();
3612
3613 // Handle enums and anonymous structs.
3614 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3615 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3616 while (OrigRec->isAnonymousStructOrUnion())
3617 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3618
3619 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3620 if (OrigDC == CurContext) {
3621 Diag(Using->getLocation(),
3622 diag::err_using_decl_nested_name_specifier_is_current_class)
3623 << Using->getNestedNameRange();
3624 Diag(Orig->getLocation(), diag::note_using_decl_target);
3625 return true;
3626 }
3627
3628 Diag(Using->getNestedNameRange().getBegin(),
3629 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3630 << Using->getTargetNestedNameDecl()
3631 << cast<CXXRecordDecl>(CurContext)
3632 << Using->getNestedNameRange();
3633 Diag(Orig->getLocation(), diag::note_using_decl_target);
3634 return true;
3635 }
3636 }
3637
3638 if (Previous.empty()) return false;
3639
3640 NamedDecl *Target = Orig;
3641 if (isa<UsingShadowDecl>(Target))
3642 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3643
John McCalld7533ec2009-12-11 02:33:26 +00003644 // If the target happens to be one of the previous declarations, we
3645 // don't have a conflict.
3646 //
3647 // FIXME: but we might be increasing its access, in which case we
3648 // should redeclare it.
3649 NamedDecl *NonTag = 0, *Tag = 0;
3650 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3651 I != E; ++I) {
3652 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003653 bool Result;
3654 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3655 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003656
3657 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3658 }
3659
John McCall9f54ad42009-12-10 09:41:52 +00003660 if (Target->isFunctionOrFunctionTemplate()) {
3661 FunctionDecl *FD;
3662 if (isa<FunctionTemplateDecl>(Target))
3663 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3664 else
3665 FD = cast<FunctionDecl>(Target);
3666
3667 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003668 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003669 case Ovl_Overload:
3670 return false;
3671
3672 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003673 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003674 break;
3675
3676 // We found a decl with the exact signature.
3677 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003678 // If we're in a record, we want to hide the target, so we
3679 // return true (without a diagnostic) to tell the caller not to
3680 // build a shadow decl.
3681 if (CurContext->isRecord())
3682 return true;
3683
3684 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003685 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003686 break;
3687 }
3688
3689 Diag(Target->getLocation(), diag::note_using_decl_target);
3690 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3691 return true;
3692 }
3693
3694 // Target is not a function.
3695
John McCall9f54ad42009-12-10 09:41:52 +00003696 if (isa<TagDecl>(Target)) {
3697 // No conflict between a tag and a non-tag.
3698 if (!Tag) return false;
3699
John McCall41ce66f2009-12-10 19:51:03 +00003700 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003701 Diag(Target->getLocation(), diag::note_using_decl_target);
3702 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3703 return true;
3704 }
3705
3706 // No conflict between a tag and a non-tag.
3707 if (!NonTag) return false;
3708
John McCall41ce66f2009-12-10 19:51:03 +00003709 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003710 Diag(Target->getLocation(), diag::note_using_decl_target);
3711 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3712 return true;
3713}
3714
John McCall9488ea12009-11-17 05:59:44 +00003715/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003716UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003717 UsingDecl *UD,
3718 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003719
3720 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003721 NamedDecl *Target = Orig;
3722 if (isa<UsingShadowDecl>(Target)) {
3723 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3724 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003725 }
3726
3727 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003728 = UsingShadowDecl::Create(Context, CurContext,
3729 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003730 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003731
3732 Shadow->setAccess(UD->getAccess());
3733 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3734 Shadow->setInvalidDecl();
3735
John McCall9488ea12009-11-17 05:59:44 +00003736 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003737 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003738 else
John McCall604e7f12009-12-08 07:46:18 +00003739 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003740
John McCall604e7f12009-12-08 07:46:18 +00003741
John McCall9f54ad42009-12-10 09:41:52 +00003742 return Shadow;
3743}
John McCall604e7f12009-12-08 07:46:18 +00003744
John McCall9f54ad42009-12-10 09:41:52 +00003745/// Hides a using shadow declaration. This is required by the current
3746/// using-decl implementation when a resolvable using declaration in a
3747/// class is followed by a declaration which would hide or override
3748/// one or more of the using decl's targets; for example:
3749///
3750/// struct Base { void foo(int); };
3751/// struct Derived : Base {
3752/// using Base::foo;
3753/// void foo(int);
3754/// };
3755///
3756/// The governing language is C++03 [namespace.udecl]p12:
3757///
3758/// When a using-declaration brings names from a base class into a
3759/// derived class scope, member functions in the derived class
3760/// override and/or hide member functions with the same name and
3761/// parameter types in a base class (rather than conflicting).
3762///
3763/// There are two ways to implement this:
3764/// (1) optimistically create shadow decls when they're not hidden
3765/// by existing declarations, or
3766/// (2) don't create any shadow decls (or at least don't make them
3767/// visible) until we've fully parsed/instantiated the class.
3768/// The problem with (1) is that we might have to retroactively remove
3769/// a shadow decl, which requires several O(n) operations because the
3770/// decl structures are (very reasonably) not designed for removal.
3771/// (2) avoids this but is very fiddly and phase-dependent.
3772void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003773 if (Shadow->getDeclName().getNameKind() ==
3774 DeclarationName::CXXConversionFunctionName)
3775 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3776
John McCall9f54ad42009-12-10 09:41:52 +00003777 // Remove it from the DeclContext...
3778 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003779
John McCall9f54ad42009-12-10 09:41:52 +00003780 // ...and the scope, if applicable...
3781 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003782 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003783 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003784 }
3785
John McCall9f54ad42009-12-10 09:41:52 +00003786 // ...and the using decl.
3787 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3788
3789 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003790 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003791}
3792
John McCall7ba107a2009-11-18 02:36:19 +00003793/// Builds a using declaration.
3794///
3795/// \param IsInstantiation - Whether this call arises from an
3796/// instantiation of an unresolved using declaration. We treat
3797/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003798NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3799 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003800 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003801 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003802 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003803 bool IsInstantiation,
3804 bool IsTypeName,
3805 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003806 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003807 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003808 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003809
Anders Carlsson550b14b2009-08-28 05:49:21 +00003810 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00003811
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003812 if (SS.isEmpty()) {
3813 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003814 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003815 }
Mike Stump1eb44332009-09-09 15:08:12 +00003816
John McCall9f54ad42009-12-10 09:41:52 +00003817 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003818 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003819 ForRedeclaration);
3820 Previous.setHideTags(false);
3821 if (S) {
3822 LookupName(Previous, S);
3823
3824 // It is really dumb that we have to do this.
3825 LookupResult::Filter F = Previous.makeFilter();
3826 while (F.hasNext()) {
3827 NamedDecl *D = F.next();
3828 if (!isDeclInScope(D, CurContext, S))
3829 F.erase();
3830 }
3831 F.done();
3832 } else {
3833 assert(IsInstantiation && "no scope in non-instantiation");
3834 assert(CurContext->isRecord() && "scope not record in instantiation");
3835 LookupQualifiedName(Previous, CurContext);
3836 }
3837
Mike Stump1eb44332009-09-09 15:08:12 +00003838 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003839 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3840
John McCall9f54ad42009-12-10 09:41:52 +00003841 // Check for invalid redeclarations.
3842 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3843 return 0;
3844
3845 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003846 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3847 return 0;
3848
John McCallaf8e6ed2009-11-12 03:15:40 +00003849 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003850 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003851 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003852 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003853 // FIXME: not all declaration name kinds are legal here
3854 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3855 UsingLoc, TypenameLoc,
3856 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003857 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003858 } else {
3859 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003860 UsingLoc, SS.getRange(),
3861 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003862 }
John McCalled976492009-12-04 22:46:56 +00003863 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003864 D = UsingDecl::Create(Context, CurContext,
3865 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003866 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003867 }
John McCalled976492009-12-04 22:46:56 +00003868 D->setAccess(AS);
3869 CurContext->addDecl(D);
3870
3871 if (!LookupContext) return D;
3872 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003873
John McCall77bb1aa2010-05-01 00:40:08 +00003874 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003875 UD->setInvalidDecl();
3876 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003877 }
3878
John McCall604e7f12009-12-08 07:46:18 +00003879 // Look up the target name.
3880
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003881 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003882
John McCall604e7f12009-12-08 07:46:18 +00003883 // Unlike most lookups, we don't always want to hide tag
3884 // declarations: tag names are visible through the using declaration
3885 // even if hidden by ordinary names, *except* in a dependent context
3886 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003887 if (!IsInstantiation)
3888 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003889
John McCalla24dc2e2009-11-17 02:14:36 +00003890 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003891
John McCallf36e02d2009-10-09 21:13:30 +00003892 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003893 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003894 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003895 UD->setInvalidDecl();
3896 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003897 }
3898
John McCalled976492009-12-04 22:46:56 +00003899 if (R.isAmbiguous()) {
3900 UD->setInvalidDecl();
3901 return UD;
3902 }
Mike Stump1eb44332009-09-09 15:08:12 +00003903
John McCall7ba107a2009-11-18 02:36:19 +00003904 if (IsTypeName) {
3905 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003906 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003907 Diag(IdentLoc, diag::err_using_typename_non_type);
3908 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3909 Diag((*I)->getUnderlyingDecl()->getLocation(),
3910 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003911 UD->setInvalidDecl();
3912 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003913 }
3914 } else {
3915 // If we asked for a non-typename and we got a type, error out,
3916 // but only if this is an instantiation of an unresolved using
3917 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003918 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003919 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3920 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003921 UD->setInvalidDecl();
3922 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003923 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003924 }
3925
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003926 // C++0x N2914 [namespace.udecl]p6:
3927 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003928 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003929 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3930 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003931 UD->setInvalidDecl();
3932 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003933 }
Mike Stump1eb44332009-09-09 15:08:12 +00003934
John McCall9f54ad42009-12-10 09:41:52 +00003935 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3936 if (!CheckUsingShadowDecl(UD, *I, Previous))
3937 BuildUsingShadowDecl(S, UD, *I);
3938 }
John McCall9488ea12009-11-17 05:59:44 +00003939
3940 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003941}
3942
John McCall9f54ad42009-12-10 09:41:52 +00003943/// Checks that the given using declaration is not an invalid
3944/// redeclaration. Note that this is checking only for the using decl
3945/// itself, not for any ill-formedness among the UsingShadowDecls.
3946bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3947 bool isTypeName,
3948 const CXXScopeSpec &SS,
3949 SourceLocation NameLoc,
3950 const LookupResult &Prev) {
3951 // C++03 [namespace.udecl]p8:
3952 // C++0x [namespace.udecl]p10:
3953 // A using-declaration is a declaration and can therefore be used
3954 // repeatedly where (and only where) multiple declarations are
3955 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00003956 //
John McCall8a726212010-11-29 18:01:58 +00003957 // That's in non-member contexts.
3958 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00003959 return false;
3960
3961 NestedNameSpecifier *Qual
3962 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3963
3964 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3965 NamedDecl *D = *I;
3966
3967 bool DTypename;
3968 NestedNameSpecifier *DQual;
3969 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3970 DTypename = UD->isTypeName();
3971 DQual = UD->getTargetNestedNameDecl();
3972 } else if (UnresolvedUsingValueDecl *UD
3973 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3974 DTypename = false;
3975 DQual = UD->getTargetNestedNameSpecifier();
3976 } else if (UnresolvedUsingTypenameDecl *UD
3977 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3978 DTypename = true;
3979 DQual = UD->getTargetNestedNameSpecifier();
3980 } else continue;
3981
3982 // using decls differ if one says 'typename' and the other doesn't.
3983 // FIXME: non-dependent using decls?
3984 if (isTypeName != DTypename) continue;
3985
3986 // using decls differ if they name different scopes (but note that
3987 // template instantiation can cause this check to trigger when it
3988 // didn't before instantiation).
3989 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3990 Context.getCanonicalNestedNameSpecifier(DQual))
3991 continue;
3992
3993 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003994 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003995 return true;
3996 }
3997
3998 return false;
3999}
4000
John McCall604e7f12009-12-08 07:46:18 +00004001
John McCalled976492009-12-04 22:46:56 +00004002/// Checks that the given nested-name qualifier used in a using decl
4003/// in the current context is appropriately related to the current
4004/// scope. If an error is found, diagnoses it and returns true.
4005bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4006 const CXXScopeSpec &SS,
4007 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004008 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004009
John McCall604e7f12009-12-08 07:46:18 +00004010 if (!CurContext->isRecord()) {
4011 // C++03 [namespace.udecl]p3:
4012 // C++0x [namespace.udecl]p8:
4013 // A using-declaration for a class member shall be a member-declaration.
4014
4015 // If we weren't able to compute a valid scope, it must be a
4016 // dependent class scope.
4017 if (!NamedContext || NamedContext->isRecord()) {
4018 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4019 << SS.getRange();
4020 return true;
4021 }
4022
4023 // Otherwise, everything is known to be fine.
4024 return false;
4025 }
4026
4027 // The current scope is a record.
4028
4029 // If the named context is dependent, we can't decide much.
4030 if (!NamedContext) {
4031 // FIXME: in C++0x, we can diagnose if we can prove that the
4032 // nested-name-specifier does not refer to a base class, which is
4033 // still possible in some cases.
4034
4035 // Otherwise we have to conservatively report that things might be
4036 // okay.
4037 return false;
4038 }
4039
4040 if (!NamedContext->isRecord()) {
4041 // Ideally this would point at the last name in the specifier,
4042 // but we don't have that level of source info.
4043 Diag(SS.getRange().getBegin(),
4044 diag::err_using_decl_nested_name_specifier_is_not_class)
4045 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4046 return true;
4047 }
4048
4049 if (getLangOptions().CPlusPlus0x) {
4050 // C++0x [namespace.udecl]p3:
4051 // In a using-declaration used as a member-declaration, the
4052 // nested-name-specifier shall name a base class of the class
4053 // being defined.
4054
4055 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4056 cast<CXXRecordDecl>(NamedContext))) {
4057 if (CurContext == NamedContext) {
4058 Diag(NameLoc,
4059 diag::err_using_decl_nested_name_specifier_is_current_class)
4060 << SS.getRange();
4061 return true;
4062 }
4063
4064 Diag(SS.getRange().getBegin(),
4065 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4066 << (NestedNameSpecifier*) SS.getScopeRep()
4067 << cast<CXXRecordDecl>(CurContext)
4068 << SS.getRange();
4069 return true;
4070 }
4071
4072 return false;
4073 }
4074
4075 // C++03 [namespace.udecl]p4:
4076 // A using-declaration used as a member-declaration shall refer
4077 // to a member of a base class of the class being defined [etc.].
4078
4079 // Salient point: SS doesn't have to name a base class as long as
4080 // lookup only finds members from base classes. Therefore we can
4081 // diagnose here only if we can prove that that can't happen,
4082 // i.e. if the class hierarchies provably don't intersect.
4083
4084 // TODO: it would be nice if "definitely valid" results were cached
4085 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4086 // need to be repeated.
4087
4088 struct UserData {
4089 llvm::DenseSet<const CXXRecordDecl*> Bases;
4090
4091 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4092 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4093 Data->Bases.insert(Base);
4094 return true;
4095 }
4096
4097 bool hasDependentBases(const CXXRecordDecl *Class) {
4098 return !Class->forallBases(collect, this);
4099 }
4100
4101 /// Returns true if the base is dependent or is one of the
4102 /// accumulated base classes.
4103 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4104 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4105 return !Data->Bases.count(Base);
4106 }
4107
4108 bool mightShareBases(const CXXRecordDecl *Class) {
4109 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4110 }
4111 };
4112
4113 UserData Data;
4114
4115 // Returns false if we find a dependent base.
4116 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4117 return false;
4118
4119 // Returns false if the class has a dependent base or if it or one
4120 // of its bases is present in the base set of the current context.
4121 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4122 return false;
4123
4124 Diag(SS.getRange().getBegin(),
4125 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4126 << (NestedNameSpecifier*) SS.getScopeRep()
4127 << cast<CXXRecordDecl>(CurContext)
4128 << SS.getRange();
4129
4130 return true;
John McCalled976492009-12-04 22:46:56 +00004131}
4132
John McCalld226f652010-08-21 09:40:31 +00004133Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004134 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004135 SourceLocation AliasLoc,
4136 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004137 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004138 SourceLocation IdentLoc,
4139 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Anders Carlsson81c85c42009-03-28 23:53:49 +00004141 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004142 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4143 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004144
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004145 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004146 NamedDecl *PrevDecl
4147 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4148 ForRedeclaration);
4149 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4150 PrevDecl = 0;
4151
4152 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004153 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004154 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004155 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004156 // FIXME: At some point, we'll want to create the (redundant)
4157 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004158 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004159 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004160 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004163 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4164 diag::err_redefinition_different_kind;
4165 Diag(AliasLoc, DiagID) << Alias;
4166 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004167 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004168 }
4169
John McCalla24dc2e2009-11-17 02:14:36 +00004170 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004171 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004172
John McCallf36e02d2009-10-09 21:13:30 +00004173 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004174 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4175 CTC_NoKeywords, 0)) {
4176 if (R.getAsSingle<NamespaceDecl>() ||
4177 R.getAsSingle<NamespaceAliasDecl>()) {
4178 if (DeclContext *DC = computeDeclContext(SS, false))
4179 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4180 << Ident << DC << Corrected << SS.getRange()
4181 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4182 else
4183 Diag(IdentLoc, diag::err_using_directive_suggest)
4184 << Ident << Corrected
4185 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4186
4187 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4188 << Corrected;
4189
4190 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004191 } else {
4192 R.clear();
4193 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004194 }
4195 }
4196
4197 if (R.empty()) {
4198 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004199 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004200 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004203 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004204 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4205 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004206 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004207 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004208
John McCall3dbd3d52010-02-16 06:53:13 +00004209 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004210 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004211}
4212
Douglas Gregor39957dc2010-05-01 15:04:51 +00004213namespace {
4214 /// \brief Scoped object used to handle the state changes required in Sema
4215 /// to implicitly define the body of a C++ member function;
4216 class ImplicitlyDefinedFunctionScope {
4217 Sema &S;
4218 DeclContext *PreviousContext;
4219
4220 public:
4221 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4222 : S(S), PreviousContext(S.CurContext)
4223 {
4224 S.CurContext = Method;
4225 S.PushFunctionScope();
4226 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4227 }
4228
4229 ~ImplicitlyDefinedFunctionScope() {
4230 S.PopExpressionEvaluationContext();
4231 S.PopFunctionOrBlockScope();
4232 S.CurContext = PreviousContext;
4233 }
4234 };
4235}
4236
Sebastian Redl751025d2010-09-13 22:02:47 +00004237static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4238 CXXRecordDecl *D) {
4239 ASTContext &Context = Self.Context;
4240 QualType ClassType = Context.getTypeDeclType(D);
4241 DeclarationName ConstructorName
4242 = Context.DeclarationNames.getCXXConstructorName(
4243 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4244
4245 DeclContext::lookup_const_iterator Con, ConEnd;
4246 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4247 Con != ConEnd; ++Con) {
4248 // FIXME: In C++0x, a constructor template can be a default constructor.
4249 if (isa<FunctionTemplateDecl>(*Con))
4250 continue;
4251
4252 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4253 if (Constructor->isDefaultConstructor())
4254 return Constructor;
4255 }
4256 return 0;
4257}
4258
Douglas Gregor23c94db2010-07-02 17:43:08 +00004259CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4260 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004261 // C++ [class.ctor]p5:
4262 // A default constructor for a class X is a constructor of class X
4263 // that can be called without an argument. If there is no
4264 // user-declared constructor for class X, a default constructor is
4265 // implicitly declared. An implicitly-declared default constructor
4266 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004267 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4268 "Should not build implicit default constructor!");
4269
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004270 // C++ [except.spec]p14:
4271 // An implicitly declared special member function (Clause 12) shall have an
4272 // exception-specification. [...]
4273 ImplicitExceptionSpecification ExceptSpec(Context);
4274
4275 // Direct base-class destructors.
4276 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4277 BEnd = ClassDecl->bases_end();
4278 B != BEnd; ++B) {
4279 if (B->isVirtual()) // Handled below.
4280 continue;
4281
Douglas Gregor18274032010-07-03 00:47:00 +00004282 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4283 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4284 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4285 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004286 else if (CXXConstructorDecl *Constructor
4287 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004288 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004289 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004290 }
4291
4292 // Virtual base-class destructors.
4293 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4294 BEnd = ClassDecl->vbases_end();
4295 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004296 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4297 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4298 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4299 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4300 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004301 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004302 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004303 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004304 }
4305
4306 // Field destructors.
4307 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4308 FEnd = ClassDecl->field_end();
4309 F != FEnd; ++F) {
4310 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004311 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4312 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4313 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4314 ExceptSpec.CalledDecl(
4315 DeclareImplicitDefaultConstructor(FieldClassDecl));
4316 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004317 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004318 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004319 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004320 }
John McCalle23cf432010-12-14 08:05:40 +00004321
4322 FunctionProtoType::ExtProtoInfo EPI;
4323 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4324 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4325 EPI.NumExceptions = ExceptSpec.size();
4326 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004327
4328 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004329 CanQualType ClassType
4330 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4331 DeclarationName Name
4332 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004333 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004334 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004335 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004336 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004337 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004338 /*TInfo=*/0,
4339 /*isExplicit=*/false,
4340 /*isInline=*/true,
4341 /*isImplicitlyDeclared=*/true);
4342 DefaultCon->setAccess(AS_public);
4343 DefaultCon->setImplicit();
4344 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004345
4346 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004347 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4348
Douglas Gregor23c94db2010-07-02 17:43:08 +00004349 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004350 PushOnScopeChains(DefaultCon, S, false);
4351 ClassDecl->addDecl(DefaultCon);
4352
Douglas Gregor32df23e2010-07-01 22:02:46 +00004353 return DefaultCon;
4354}
4355
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004356void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4357 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004358 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004359 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004360 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004362 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004363 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004364
Douglas Gregor39957dc2010-05-01 15:04:51 +00004365 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004366 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004367 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4368 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004369 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004370 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004371 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004372 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004373 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004374
4375 SourceLocation Loc = Constructor->getLocation();
4376 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4377
4378 Constructor->setUsed();
4379 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004380}
4381
Douglas Gregor23c94db2010-07-02 17:43:08 +00004382CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004383 // C++ [class.dtor]p2:
4384 // If a class has no user-declared destructor, a destructor is
4385 // declared implicitly. An implicitly-declared destructor is an
4386 // inline public member of its class.
4387
4388 // C++ [except.spec]p14:
4389 // An implicitly declared special member function (Clause 12) shall have
4390 // an exception-specification.
4391 ImplicitExceptionSpecification ExceptSpec(Context);
4392
4393 // Direct base-class destructors.
4394 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4395 BEnd = ClassDecl->bases_end();
4396 B != BEnd; ++B) {
4397 if (B->isVirtual()) // Handled below.
4398 continue;
4399
4400 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4401 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004402 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004403 }
4404
4405 // Virtual base-class destructors.
4406 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4407 BEnd = ClassDecl->vbases_end();
4408 B != BEnd; ++B) {
4409 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4410 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004411 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004412 }
4413
4414 // Field destructors.
4415 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4416 FEnd = ClassDecl->field_end();
4417 F != FEnd; ++F) {
4418 if (const RecordType *RecordTy
4419 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4420 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004421 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004422 }
4423
Douglas Gregor4923aa22010-07-02 20:37:36 +00004424 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004425 FunctionProtoType::ExtProtoInfo EPI;
4426 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4427 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4428 EPI.NumExceptions = ExceptSpec.size();
4429 EPI.Exceptions = ExceptSpec.data();
4430 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004431
4432 CanQualType ClassType
4433 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4434 DeclarationName Name
4435 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004436 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004437 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004438 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004439 /*isInline=*/true,
4440 /*isImplicitlyDeclared=*/true);
4441 Destructor->setAccess(AS_public);
4442 Destructor->setImplicit();
4443 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004444
4445 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004446 ++ASTContext::NumImplicitDestructorsDeclared;
4447
4448 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004449 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004450 PushOnScopeChains(Destructor, S, false);
4451 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004452
4453 // This could be uniqued if it ever proves significant.
4454 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4455
4456 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004457
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004458 return Destructor;
4459}
4460
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004461void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004462 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004463 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004464 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004465 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004466 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004467
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004468 if (Destructor->isInvalidDecl())
4469 return;
4470
Douglas Gregor39957dc2010-05-01 15:04:51 +00004471 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004472
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004473 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004474 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4475 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004476
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004477 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004478 Diag(CurrentLocation, diag::note_member_synthesized_at)
4479 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4480
4481 Destructor->setInvalidDecl();
4482 return;
4483 }
4484
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004485 SourceLocation Loc = Destructor->getLocation();
4486 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4487
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004488 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004489 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004490}
4491
Douglas Gregor06a9f362010-05-01 20:49:11 +00004492/// \brief Builds a statement that copies the given entity from \p From to
4493/// \c To.
4494///
4495/// This routine is used to copy the members of a class with an
4496/// implicitly-declared copy assignment operator. When the entities being
4497/// copied are arrays, this routine builds for loops to copy them.
4498///
4499/// \param S The Sema object used for type-checking.
4500///
4501/// \param Loc The location where the implicit copy is being generated.
4502///
4503/// \param T The type of the expressions being copied. Both expressions must
4504/// have this type.
4505///
4506/// \param To The expression we are copying to.
4507///
4508/// \param From The expression we are copying from.
4509///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004510/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4511/// Otherwise, it's a non-static member subobject.
4512///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004513/// \param Depth Internal parameter recording the depth of the recursion.
4514///
4515/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004516static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004517BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004518 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004519 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004520 // C++0x [class.copy]p30:
4521 // Each subobject is assigned in the manner appropriate to its type:
4522 //
4523 // - if the subobject is of class type, the copy assignment operator
4524 // for the class is used (as if by explicit qualification; that is,
4525 // ignoring any possible virtual overriding functions in more derived
4526 // classes);
4527 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4528 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4529
4530 // Look for operator=.
4531 DeclarationName Name
4532 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4533 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4534 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4535
4536 // Filter out any result that isn't a copy-assignment operator.
4537 LookupResult::Filter F = OpLookup.makeFilter();
4538 while (F.hasNext()) {
4539 NamedDecl *D = F.next();
4540 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4541 if (Method->isCopyAssignmentOperator())
4542 continue;
4543
4544 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004545 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004546 F.done();
4547
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004548 // Suppress the protected check (C++ [class.protected]) for each of the
4549 // assignment operators we found. This strange dance is required when
4550 // we're assigning via a base classes's copy-assignment operator. To
4551 // ensure that we're getting the right base class subobject (without
4552 // ambiguities), we need to cast "this" to that subobject type; to
4553 // ensure that we don't go through the virtual call mechanism, we need
4554 // to qualify the operator= name with the base class (see below). However,
4555 // this means that if the base class has a protected copy assignment
4556 // operator, the protected member access check will fail. So, we
4557 // rewrite "protected" access to "public" access in this case, since we
4558 // know by construction that we're calling from a derived class.
4559 if (CopyingBaseSubobject) {
4560 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4561 L != LEnd; ++L) {
4562 if (L.getAccess() == AS_protected)
4563 L.setAccess(AS_public);
4564 }
4565 }
4566
Douglas Gregor06a9f362010-05-01 20:49:11 +00004567 // Create the nested-name-specifier that will be used to qualify the
4568 // reference to operator=; this is required to suppress the virtual
4569 // call mechanism.
4570 CXXScopeSpec SS;
4571 SS.setRange(Loc);
4572 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4573 T.getTypePtr()));
4574
4575 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004576 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004577 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004578 /*FirstQualifierInScope=*/0, OpLookup,
4579 /*TemplateArgs=*/0,
4580 /*SuppressQualifierCheck=*/true);
4581 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004582 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004583
4584 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004585
John McCall60d7b3a2010-08-24 06:29:42 +00004586 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004587 OpEqualRef.takeAs<Expr>(),
4588 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004589 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004590 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004591
4592 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004593 }
John McCallb0207482010-03-16 06:11:48 +00004594
Douglas Gregor06a9f362010-05-01 20:49:11 +00004595 // - if the subobject is of scalar type, the built-in assignment
4596 // operator is used.
4597 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4598 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004599 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004600 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004601 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004602
4603 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004604 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004605
4606 // - if the subobject is an array, each element is assigned, in the
4607 // manner appropriate to the element type;
4608
4609 // Construct a loop over the array bounds, e.g.,
4610 //
4611 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4612 //
4613 // that will copy each of the array elements.
4614 QualType SizeType = S.Context.getSizeType();
4615
4616 // Create the iteration variable.
4617 IdentifierInfo *IterationVarName = 0;
4618 {
4619 llvm::SmallString<8> Str;
4620 llvm::raw_svector_ostream OS(Str);
4621 OS << "__i" << Depth;
4622 IterationVarName = &S.Context.Idents.get(OS.str());
4623 }
4624 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4625 IterationVarName, SizeType,
4626 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004627 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004628
4629 // Initialize the iteration variable to zero.
4630 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004631 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004632
4633 // Create a reference to the iteration variable; we'll use this several
4634 // times throughout.
4635 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00004636 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004637 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4638
4639 // Create the DeclStmt that holds the iteration variable.
4640 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4641
4642 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004643 llvm::APInt Upper
4644 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004645 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00004646 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00004647 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4648 BO_NE, S.Context.BoolTy,
4649 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004650
4651 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004652 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00004653 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4654 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004655
4656 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004657 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4658 IterationVarRef, Loc));
4659 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4660 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004661
4662 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00004663 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4664 To, From, CopyingBaseSubobject,
4665 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004666 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004667 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004668
4669 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004670 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004671 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004672 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004673 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004674}
4675
Douglas Gregora376d102010-07-02 21:50:04 +00004676/// \brief Determine whether the given class has a copy assignment operator
4677/// that accepts a const-qualified argument.
4678static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4679 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4680
4681 if (!Class->hasDeclaredCopyAssignment())
4682 S.DeclareImplicitCopyAssignment(Class);
4683
4684 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4685 DeclarationName OpName
4686 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4687
4688 DeclContext::lookup_const_iterator Op, OpEnd;
4689 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4690 // C++ [class.copy]p9:
4691 // A user-declared copy assignment operator is a non-static non-template
4692 // member function of class X with exactly one parameter of type X, X&,
4693 // const X&, volatile X& or const volatile X&.
4694 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4695 if (!Method)
4696 continue;
4697
4698 if (Method->isStatic())
4699 continue;
4700 if (Method->getPrimaryTemplate())
4701 continue;
4702 const FunctionProtoType *FnType =
4703 Method->getType()->getAs<FunctionProtoType>();
4704 assert(FnType && "Overloaded operator has no prototype.");
4705 // Don't assert on this; an invalid decl might have been left in the AST.
4706 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4707 continue;
4708 bool AcceptsConst = true;
4709 QualType ArgType = FnType->getArgType(0);
4710 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4711 ArgType = Ref->getPointeeType();
4712 // Is it a non-const lvalue reference?
4713 if (!ArgType.isConstQualified())
4714 AcceptsConst = false;
4715 }
4716 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4717 continue;
4718
4719 // We have a single argument of type cv X or cv X&, i.e. we've found the
4720 // copy assignment operator. Return whether it accepts const arguments.
4721 return AcceptsConst;
4722 }
4723 assert(Class->isInvalidDecl() &&
4724 "No copy assignment operator declared in valid code.");
4725 return false;
4726}
4727
Douglas Gregor23c94db2010-07-02 17:43:08 +00004728CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004729 // Note: The following rules are largely analoguous to the copy
4730 // constructor rules. Note that virtual bases are not taken into account
4731 // for determining the argument type of the operator. Note also that
4732 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004733
4734
Douglas Gregord3c35902010-07-01 16:36:15 +00004735 // C++ [class.copy]p10:
4736 // If the class definition does not explicitly declare a copy
4737 // assignment operator, one is declared implicitly.
4738 // The implicitly-defined copy assignment operator for a class X
4739 // will have the form
4740 //
4741 // X& X::operator=(const X&)
4742 //
4743 // if
4744 bool HasConstCopyAssignment = true;
4745
4746 // -- each direct base class B of X has a copy assignment operator
4747 // whose parameter is of type const B&, const volatile B& or B,
4748 // and
4749 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4750 BaseEnd = ClassDecl->bases_end();
4751 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4752 assert(!Base->getType()->isDependentType() &&
4753 "Cannot generate implicit members for class with dependent bases.");
4754 const CXXRecordDecl *BaseClassDecl
4755 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004756 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004757 }
4758
4759 // -- for all the nonstatic data members of X that are of a class
4760 // type M (or array thereof), each such class type has a copy
4761 // assignment operator whose parameter is of type const M&,
4762 // const volatile M& or M.
4763 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4764 FieldEnd = ClassDecl->field_end();
4765 HasConstCopyAssignment && Field != FieldEnd;
4766 ++Field) {
4767 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4768 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4769 const CXXRecordDecl *FieldClassDecl
4770 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004771 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004772 }
4773 }
4774
4775 // Otherwise, the implicitly declared copy assignment operator will
4776 // have the form
4777 //
4778 // X& X::operator=(X&)
4779 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4780 QualType RetType = Context.getLValueReferenceType(ArgType);
4781 if (HasConstCopyAssignment)
4782 ArgType = ArgType.withConst();
4783 ArgType = Context.getLValueReferenceType(ArgType);
4784
Douglas Gregorb87786f2010-07-01 17:48:08 +00004785 // C++ [except.spec]p14:
4786 // An implicitly declared special member function (Clause 12) shall have an
4787 // exception-specification. [...]
4788 ImplicitExceptionSpecification ExceptSpec(Context);
4789 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4790 BaseEnd = ClassDecl->bases_end();
4791 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004792 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004793 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004794
4795 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4796 DeclareImplicitCopyAssignment(BaseClassDecl);
4797
Douglas Gregorb87786f2010-07-01 17:48:08 +00004798 if (CXXMethodDecl *CopyAssign
4799 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4800 ExceptSpec.CalledDecl(CopyAssign);
4801 }
4802 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4803 FieldEnd = ClassDecl->field_end();
4804 Field != FieldEnd;
4805 ++Field) {
4806 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4807 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004808 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004809 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004810
4811 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4812 DeclareImplicitCopyAssignment(FieldClassDecl);
4813
Douglas Gregorb87786f2010-07-01 17:48:08 +00004814 if (CXXMethodDecl *CopyAssign
4815 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4816 ExceptSpec.CalledDecl(CopyAssign);
4817 }
4818 }
4819
Douglas Gregord3c35902010-07-01 16:36:15 +00004820 // An implicitly-declared copy assignment operator is an inline public
4821 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00004822 FunctionProtoType::ExtProtoInfo EPI;
4823 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4824 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4825 EPI.NumExceptions = ExceptSpec.size();
4826 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00004827 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004828 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004829 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004830 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00004831 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00004832 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004833 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004834 /*isInline=*/true);
4835 CopyAssignment->setAccess(AS_public);
4836 CopyAssignment->setImplicit();
4837 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004838
4839 // Add the parameter to the operator.
4840 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4841 ClassDecl->getLocation(),
4842 /*Id=*/0,
4843 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004844 SC_None,
4845 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004846 CopyAssignment->setParams(&FromParam, 1);
4847
Douglas Gregora376d102010-07-02 21:50:04 +00004848 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004849 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4850
Douglas Gregor23c94db2010-07-02 17:43:08 +00004851 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004852 PushOnScopeChains(CopyAssignment, S, false);
4853 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004854
4855 AddOverriddenMethods(ClassDecl, CopyAssignment);
4856 return CopyAssignment;
4857}
4858
Douglas Gregor06a9f362010-05-01 20:49:11 +00004859void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4860 CXXMethodDecl *CopyAssignOperator) {
4861 assert((CopyAssignOperator->isImplicit() &&
4862 CopyAssignOperator->isOverloadedOperator() &&
4863 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004864 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004865 "DefineImplicitCopyAssignment called for wrong function");
4866
4867 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4868
4869 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4870 CopyAssignOperator->setInvalidDecl();
4871 return;
4872 }
4873
4874 CopyAssignOperator->setUsed();
4875
4876 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004877 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004878
4879 // C++0x [class.copy]p30:
4880 // The implicitly-defined or explicitly-defaulted copy assignment operator
4881 // for a non-union class X performs memberwise copy assignment of its
4882 // subobjects. The direct base classes of X are assigned first, in the
4883 // order of their declaration in the base-specifier-list, and then the
4884 // immediate non-static data members of X are assigned, in the order in
4885 // which they were declared in the class definition.
4886
4887 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004888 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004889
4890 // The parameter for the "other" object, which we are copying from.
4891 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4892 Qualifiers OtherQuals = Other->getType().getQualifiers();
4893 QualType OtherRefType = Other->getType();
4894 if (const LValueReferenceType *OtherRef
4895 = OtherRefType->getAs<LValueReferenceType>()) {
4896 OtherRefType = OtherRef->getPointeeType();
4897 OtherQuals = OtherRefType.getQualifiers();
4898 }
4899
4900 // Our location for everything implicitly-generated.
4901 SourceLocation Loc = CopyAssignOperator->getLocation();
4902
4903 // Construct a reference to the "other" object. We'll be using this
4904 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00004905 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004906 assert(OtherRef && "Reference to parameter cannot fail!");
4907
4908 // Construct the "this" pointer. We'll be using this throughout the generated
4909 // ASTs.
4910 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4911 assert(This && "Reference to this cannot fail!");
4912
4913 // Assign base classes.
4914 bool Invalid = false;
4915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4916 E = ClassDecl->bases_end(); Base != E; ++Base) {
4917 // Form the assignment:
4918 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4919 QualType BaseType = Base->getType().getUnqualifiedType();
4920 CXXRecordDecl *BaseClassDecl = 0;
4921 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4922 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4923 else {
4924 Invalid = true;
4925 continue;
4926 }
4927
John McCallf871d0c2010-08-07 06:22:56 +00004928 CXXCastPath BasePath;
4929 BasePath.push_back(Base);
4930
Douglas Gregor06a9f362010-05-01 20:49:11 +00004931 // Construct the "from" expression, which is an implicit cast to the
4932 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00004933 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004934 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004935 CK_UncheckedDerivedToBase,
4936 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004937
4938 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004939 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004940
4941 // Implicitly cast "this" to the appropriately-qualified base type.
4942 Expr *ToE = To.takeAs<Expr>();
4943 ImpCastExprToType(ToE,
4944 Context.getCVRQualifiedType(BaseType,
4945 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004946 CK_UncheckedDerivedToBase,
4947 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004948 To = Owned(ToE);
4949
4950 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004951 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004952 To.get(), From,
4953 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004954 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004955 Diag(CurrentLocation, diag::note_member_synthesized_at)
4956 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4957 CopyAssignOperator->setInvalidDecl();
4958 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004959 }
4960
4961 // Success! Record the copy.
4962 Statements.push_back(Copy.takeAs<Expr>());
4963 }
4964
4965 // \brief Reference to the __builtin_memcpy function.
4966 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00004967 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00004968 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004969
4970 // Assign non-static members.
4971 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4972 FieldEnd = ClassDecl->field_end();
4973 Field != FieldEnd; ++Field) {
4974 // Check for members of reference type; we can't copy those.
4975 if (Field->getType()->isReferenceType()) {
4976 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4977 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4978 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004979 Diag(CurrentLocation, diag::note_member_synthesized_at)
4980 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004981 Invalid = true;
4982 continue;
4983 }
4984
4985 // Check for members of const-qualified, non-class type.
4986 QualType BaseType = Context.getBaseElementType(Field->getType());
4987 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4988 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4989 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4990 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004991 Diag(CurrentLocation, diag::note_member_synthesized_at)
4992 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004993 Invalid = true;
4994 continue;
4995 }
4996
4997 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00004998 if (FieldType->isIncompleteArrayType()) {
4999 assert(ClassDecl->hasFlexibleArrayMember() &&
5000 "Incomplete array type is not valid");
5001 continue;
5002 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005003
5004 // Build references to the field in the object we're copying from and to.
5005 CXXScopeSpec SS; // Intentionally empty
5006 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5007 LookupMemberName);
5008 MemberLookup.addDecl(*Field);
5009 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005010 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005011 Loc, /*IsArrow=*/false,
5012 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005013 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005014 Loc, /*IsArrow=*/true,
5015 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005016 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5017 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5018
5019 // If the field should be copied with __builtin_memcpy rather than via
5020 // explicit assignments, do so. This optimization only applies for arrays
5021 // of scalars and arrays of class type with trivial copy-assignment
5022 // operators.
5023 if (FieldType->isArrayType() &&
5024 (!BaseType->isRecordType() ||
5025 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5026 ->hasTrivialCopyAssignment())) {
5027 // Compute the size of the memory buffer to be copied.
5028 QualType SizeType = Context.getSizeType();
5029 llvm::APInt Size(Context.getTypeSize(SizeType),
5030 Context.getTypeSizeInChars(BaseType).getQuantity());
5031 for (const ConstantArrayType *Array
5032 = Context.getAsConstantArrayType(FieldType);
5033 Array;
5034 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005035 llvm::APInt ArraySize
5036 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005037 Size *= ArraySize;
5038 }
5039
5040 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005041 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5042 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005043
5044 bool NeedsCollectableMemCpy =
5045 (BaseType->isRecordType() &&
5046 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5047
5048 if (NeedsCollectableMemCpy) {
5049 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005050 // Create a reference to the __builtin_objc_memmove_collectable function.
5051 LookupResult R(*this,
5052 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005053 Loc, LookupOrdinaryName);
5054 LookupName(R, TUScope, true);
5055
5056 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5057 if (!CollectableMemCpy) {
5058 // Something went horribly wrong earlier, and we will have
5059 // complained about it.
5060 Invalid = true;
5061 continue;
5062 }
5063
5064 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5065 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005066 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005067 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5068 }
5069 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005070 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005071 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005072 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5073 LookupOrdinaryName);
5074 LookupName(R, TUScope, true);
5075
5076 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5077 if (!BuiltinMemCpy) {
5078 // Something went horribly wrong earlier, and we will have complained
5079 // about it.
5080 Invalid = true;
5081 continue;
5082 }
5083
5084 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5085 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005086 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005087 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5088 }
5089
John McCallca0408f2010-08-23 06:44:23 +00005090 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005091 CallArgs.push_back(To.takeAs<Expr>());
5092 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005093 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005094 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005095 if (NeedsCollectableMemCpy)
5096 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005097 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005098 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005099 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005100 else
5101 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005102 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005103 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005104 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005105
Douglas Gregor06a9f362010-05-01 20:49:11 +00005106 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5107 Statements.push_back(Call.takeAs<Expr>());
5108 continue;
5109 }
5110
5111 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005112 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005113 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005114 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005115 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005116 Diag(CurrentLocation, diag::note_member_synthesized_at)
5117 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5118 CopyAssignOperator->setInvalidDecl();
5119 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005120 }
5121
5122 // Success! Record the copy.
5123 Statements.push_back(Copy.takeAs<Stmt>());
5124 }
5125
5126 if (!Invalid) {
5127 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005128 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005129
John McCall60d7b3a2010-08-24 06:29:42 +00005130 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005131 if (Return.isInvalid())
5132 Invalid = true;
5133 else {
5134 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005135
5136 if (Trap.hasErrorOccurred()) {
5137 Diag(CurrentLocation, diag::note_member_synthesized_at)
5138 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5139 Invalid = true;
5140 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005141 }
5142 }
5143
5144 if (Invalid) {
5145 CopyAssignOperator->setInvalidDecl();
5146 return;
5147 }
5148
John McCall60d7b3a2010-08-24 06:29:42 +00005149 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005150 /*isStmtExpr=*/false);
5151 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5152 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005153}
5154
Douglas Gregor23c94db2010-07-02 17:43:08 +00005155CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5156 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005157 // C++ [class.copy]p4:
5158 // If the class definition does not explicitly declare a copy
5159 // constructor, one is declared implicitly.
5160
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005161 // C++ [class.copy]p5:
5162 // The implicitly-declared copy constructor for a class X will
5163 // have the form
5164 //
5165 // X::X(const X&)
5166 //
5167 // if
5168 bool HasConstCopyConstructor = true;
5169
5170 // -- each direct or virtual base class B of X has a copy
5171 // constructor whose first parameter is of type const B& or
5172 // const volatile B&, and
5173 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5174 BaseEnd = ClassDecl->bases_end();
5175 HasConstCopyConstructor && Base != BaseEnd;
5176 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005177 // Virtual bases are handled below.
5178 if (Base->isVirtual())
5179 continue;
5180
Douglas Gregor22584312010-07-02 23:41:54 +00005181 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005182 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005183 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5184 DeclareImplicitCopyConstructor(BaseClassDecl);
5185
Douglas Gregor598a8542010-07-01 18:27:03 +00005186 HasConstCopyConstructor
5187 = BaseClassDecl->hasConstCopyConstructor(Context);
5188 }
5189
5190 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5191 BaseEnd = ClassDecl->vbases_end();
5192 HasConstCopyConstructor && Base != BaseEnd;
5193 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005194 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005195 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005196 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5197 DeclareImplicitCopyConstructor(BaseClassDecl);
5198
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005199 HasConstCopyConstructor
5200 = BaseClassDecl->hasConstCopyConstructor(Context);
5201 }
5202
5203 // -- for all the nonstatic data members of X that are of a
5204 // class type M (or array thereof), each such class type
5205 // has a copy constructor whose first parameter is of type
5206 // const M& or const volatile M&.
5207 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5208 FieldEnd = ClassDecl->field_end();
5209 HasConstCopyConstructor && Field != FieldEnd;
5210 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005211 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005212 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005213 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005214 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005215 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5216 DeclareImplicitCopyConstructor(FieldClassDecl);
5217
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005218 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005219 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005220 }
5221 }
5222
5223 // Otherwise, the implicitly declared copy constructor will have
5224 // the form
5225 //
5226 // X::X(X&)
5227 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5228 QualType ArgType = ClassType;
5229 if (HasConstCopyConstructor)
5230 ArgType = ArgType.withConst();
5231 ArgType = Context.getLValueReferenceType(ArgType);
5232
Douglas Gregor0d405db2010-07-01 20:59:04 +00005233 // C++ [except.spec]p14:
5234 // An implicitly declared special member function (Clause 12) shall have an
5235 // exception-specification. [...]
5236 ImplicitExceptionSpecification ExceptSpec(Context);
5237 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5238 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5239 BaseEnd = ClassDecl->bases_end();
5240 Base != BaseEnd;
5241 ++Base) {
5242 // Virtual bases are handled below.
5243 if (Base->isVirtual())
5244 continue;
5245
Douglas Gregor22584312010-07-02 23:41:54 +00005246 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005247 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005248 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5249 DeclareImplicitCopyConstructor(BaseClassDecl);
5250
Douglas Gregor0d405db2010-07-01 20:59:04 +00005251 if (CXXConstructorDecl *CopyConstructor
5252 = BaseClassDecl->getCopyConstructor(Context, Quals))
5253 ExceptSpec.CalledDecl(CopyConstructor);
5254 }
5255 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5256 BaseEnd = ClassDecl->vbases_end();
5257 Base != BaseEnd;
5258 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005259 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005260 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005261 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5262 DeclareImplicitCopyConstructor(BaseClassDecl);
5263
Douglas Gregor0d405db2010-07-01 20:59:04 +00005264 if (CXXConstructorDecl *CopyConstructor
5265 = BaseClassDecl->getCopyConstructor(Context, Quals))
5266 ExceptSpec.CalledDecl(CopyConstructor);
5267 }
5268 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5269 FieldEnd = ClassDecl->field_end();
5270 Field != FieldEnd;
5271 ++Field) {
5272 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5273 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005274 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005275 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005276 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5277 DeclareImplicitCopyConstructor(FieldClassDecl);
5278
Douglas Gregor0d405db2010-07-01 20:59:04 +00005279 if (CXXConstructorDecl *CopyConstructor
5280 = FieldClassDecl->getCopyConstructor(Context, Quals))
5281 ExceptSpec.CalledDecl(CopyConstructor);
5282 }
5283 }
5284
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005285 // An implicitly-declared copy constructor is an inline public
5286 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005287 FunctionProtoType::ExtProtoInfo EPI;
5288 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5289 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5290 EPI.NumExceptions = ExceptSpec.size();
5291 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005292 DeclarationName Name
5293 = Context.DeclarationNames.getCXXConstructorName(
5294 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005295 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005296 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005297 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005298 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005299 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005300 /*TInfo=*/0,
5301 /*isExplicit=*/false,
5302 /*isInline=*/true,
5303 /*isImplicitlyDeclared=*/true);
5304 CopyConstructor->setAccess(AS_public);
5305 CopyConstructor->setImplicit();
5306 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5307
Douglas Gregor22584312010-07-02 23:41:54 +00005308 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005309 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5310
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005311 // Add the parameter to the constructor.
5312 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5313 ClassDecl->getLocation(),
5314 /*IdentifierInfo=*/0,
5315 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005316 SC_None,
5317 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005318 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005319 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005320 PushOnScopeChains(CopyConstructor, S, false);
5321 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005322
5323 return CopyConstructor;
5324}
5325
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005326void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5327 CXXConstructorDecl *CopyConstructor,
5328 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005329 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005330 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005331 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005332 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005333
Anders Carlsson63010a72010-04-23 16:24:12 +00005334 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005335 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005336
Douglas Gregor39957dc2010-05-01 15:04:51 +00005337 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005338 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005339
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005340 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5341 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005342 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005343 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005344 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005345 } else {
5346 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5347 CopyConstructor->getLocation(),
5348 MultiStmtArg(*this, 0, 0),
5349 /*isStmtExpr=*/false)
5350 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005351 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005352
5353 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005354}
5355
John McCall60d7b3a2010-08-24 06:29:42 +00005356ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005357Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005358 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005359 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005360 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005361 unsigned ConstructKind,
5362 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005363 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005364
Douglas Gregor2f599792010-04-02 18:24:57 +00005365 // C++0x [class.copy]p34:
5366 // When certain criteria are met, an implementation is allowed to
5367 // omit the copy/move construction of a class object, even if the
5368 // copy/move constructor and/or destructor for the object have
5369 // side effects. [...]
5370 // - when a temporary class object that has not been bound to a
5371 // reference (12.2) would be copied/moved to a class object
5372 // with the same cv-unqualified type, the copy/move operation
5373 // can be omitted by constructing the temporary object
5374 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005375 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5376 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005377 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005378 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005379 }
Mike Stump1eb44332009-09-09 15:08:12 +00005380
5381 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005382 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005383 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005384}
5385
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005386/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5387/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005388ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005389Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5390 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005391 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005392 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005393 unsigned ConstructKind,
5394 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005395 unsigned NumExprs = ExprArgs.size();
5396 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005397
Douglas Gregor7edfb692009-11-23 12:27:39 +00005398 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005399 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005400 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005401 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005402 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5403 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005404}
5405
Mike Stump1eb44332009-09-09 15:08:12 +00005406bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005407 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005408 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005409 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005410 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005411 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005412 move(Exprs), false, CXXConstructExpr::CK_Complete,
5413 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005414 if (TempResult.isInvalid())
5415 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005416
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005417 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005418 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005419 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005420 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005421 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005422
Anders Carlssonfe2de492009-08-25 05:18:00 +00005423 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005424}
5425
John McCall68c6c9a2010-02-02 09:10:11 +00005426void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5427 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005428 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005429 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005430 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005431 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005432 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005433 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005434 << VD->getDeclName()
5435 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005436
John McCallae792222010-09-18 05:25:11 +00005437 // TODO: this should be re-enabled for static locals by !CXAAtExit
5438 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005439 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005440 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005441}
5442
Mike Stump1eb44332009-09-09 15:08:12 +00005443/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005444/// ActOnDeclarator, when a C++ direct initializer is present.
5445/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005446void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005447 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005448 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005449 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005450 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005451
5452 // If there is no declaration, there was an error parsing it. Just ignore
5453 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005454 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005455 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005456
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005457 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5458 if (!VDecl) {
5459 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5460 RealDecl->setInvalidDecl();
5461 return;
5462 }
5463
Douglas Gregor83ddad32009-08-26 21:14:46 +00005464 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005465 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005466 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5467 //
5468 // Clients that want to distinguish between the two forms, can check for
5469 // direct initializer using VarDecl::hasCXXDirectInitializer().
5470 // A major benefit is that clients that don't particularly care about which
5471 // exactly form was it (like the CodeGen) can handle both cases without
5472 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005473
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005474 // C++ 8.5p11:
5475 // The form of initialization (using parentheses or '=') is generally
5476 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005477 // class type.
5478
Douglas Gregor4dffad62010-02-11 22:55:30 +00005479 if (!VDecl->getType()->isDependentType() &&
5480 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005481 diag::err_typecheck_decl_incomplete_type)) {
5482 VDecl->setInvalidDecl();
5483 return;
5484 }
5485
Douglas Gregor90f93822009-12-22 22:17:25 +00005486 // The variable can not have an abstract class type.
5487 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5488 diag::err_abstract_type_in_decl,
5489 AbstractVariableType))
5490 VDecl->setInvalidDecl();
5491
Sebastian Redl31310a22010-02-01 20:16:42 +00005492 const VarDecl *Def;
5493 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005494 Diag(VDecl->getLocation(), diag::err_redefinition)
5495 << VDecl->getDeclName();
5496 Diag(Def->getLocation(), diag::note_previous_definition);
5497 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005498 return;
5499 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005500
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005501 // C++ [class.static.data]p4
5502 // If a static data member is of const integral or const
5503 // enumeration type, its declaration in the class definition can
5504 // specify a constant-initializer which shall be an integral
5505 // constant expression (5.19). In that case, the member can appear
5506 // in integral constant expressions. The member shall still be
5507 // defined in a namespace scope if it is used in the program and the
5508 // namespace scope definition shall not contain an initializer.
5509 //
5510 // We already performed a redefinition check above, but for static
5511 // data members we also need to check whether there was an in-class
5512 // declaration with an initializer.
5513 const VarDecl* PrevInit = 0;
5514 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5515 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5516 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5517 return;
5518 }
5519
Douglas Gregor4dffad62010-02-11 22:55:30 +00005520 // If either the declaration has a dependent type or if any of the
5521 // expressions is type-dependent, we represent the initialization
5522 // via a ParenListExpr for later use during template instantiation.
5523 if (VDecl->getType()->isDependentType() ||
5524 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5525 // Let clients know that initialization was done with a direct initializer.
5526 VDecl->setCXXDirectInitializer(true);
5527
5528 // Store the initialization expressions as a ParenListExpr.
5529 unsigned NumExprs = Exprs.size();
5530 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5531 (Expr **)Exprs.release(),
5532 NumExprs, RParenLoc));
5533 return;
5534 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005535
5536 // Capture the variable that is being initialized and the style of
5537 // initialization.
5538 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5539
5540 // FIXME: Poor source location information.
5541 InitializationKind Kind
5542 = InitializationKind::CreateDirect(VDecl->getLocation(),
5543 LParenLoc, RParenLoc);
5544
5545 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005546 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005547 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005548 if (Result.isInvalid()) {
5549 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005550 return;
5551 }
John McCallb4eb64d2010-10-08 02:01:28 +00005552
5553 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005554
Douglas Gregor53c374f2010-12-07 00:41:46 +00005555 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00005556 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005557 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005558
John McCall4204f072010-08-02 21:13:48 +00005559 if (!VDecl->isInvalidDecl() &&
5560 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005561 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005562 !VDecl->getInit()->isConstantInitializer(Context,
5563 VDecl->getType()->isReferenceType()))
5564 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5565 << VDecl->getInit()->getSourceRange();
5566
John McCall68c6c9a2010-02-02 09:10:11 +00005567 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5568 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005569}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005570
Douglas Gregor39da0b82009-09-09 23:08:42 +00005571/// \brief Given a constructor and the set of arguments provided for the
5572/// constructor, convert the arguments and add any required default arguments
5573/// to form a proper call to this constructor.
5574///
5575/// \returns true if an error occurred, false otherwise.
5576bool
5577Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5578 MultiExprArg ArgsPtr,
5579 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005580 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005581 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5582 unsigned NumArgs = ArgsPtr.size();
5583 Expr **Args = (Expr **)ArgsPtr.get();
5584
5585 const FunctionProtoType *Proto
5586 = Constructor->getType()->getAs<FunctionProtoType>();
5587 assert(Proto && "Constructor without a prototype?");
5588 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005589
5590 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005591 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005592 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005593 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005594 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005595
5596 VariadicCallType CallType =
5597 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5598 llvm::SmallVector<Expr *, 8> AllArgs;
5599 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5600 Proto, 0, Args, NumArgs, AllArgs,
5601 CallType);
5602 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5603 ConvertedArgs.push_back(AllArgs[i]);
5604 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005605}
5606
Anders Carlsson20d45d22009-12-12 00:32:00 +00005607static inline bool
5608CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5609 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005610 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005611 if (isa<NamespaceDecl>(DC)) {
5612 return SemaRef.Diag(FnDecl->getLocation(),
5613 diag::err_operator_new_delete_declared_in_namespace)
5614 << FnDecl->getDeclName();
5615 }
5616
5617 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005618 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005619 return SemaRef.Diag(FnDecl->getLocation(),
5620 diag::err_operator_new_delete_declared_static)
5621 << FnDecl->getDeclName();
5622 }
5623
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005624 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005625}
5626
Anders Carlsson156c78e2009-12-13 17:53:43 +00005627static inline bool
5628CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5629 CanQualType ExpectedResultType,
5630 CanQualType ExpectedFirstParamType,
5631 unsigned DependentParamTypeDiag,
5632 unsigned InvalidParamTypeDiag) {
5633 QualType ResultType =
5634 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5635
5636 // Check that the result type is not dependent.
5637 if (ResultType->isDependentType())
5638 return SemaRef.Diag(FnDecl->getLocation(),
5639 diag::err_operator_new_delete_dependent_result_type)
5640 << FnDecl->getDeclName() << ExpectedResultType;
5641
5642 // Check that the result type is what we expect.
5643 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5644 return SemaRef.Diag(FnDecl->getLocation(),
5645 diag::err_operator_new_delete_invalid_result_type)
5646 << FnDecl->getDeclName() << ExpectedResultType;
5647
5648 // A function template must have at least 2 parameters.
5649 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5650 return SemaRef.Diag(FnDecl->getLocation(),
5651 diag::err_operator_new_delete_template_too_few_parameters)
5652 << FnDecl->getDeclName();
5653
5654 // The function decl must have at least 1 parameter.
5655 if (FnDecl->getNumParams() == 0)
5656 return SemaRef.Diag(FnDecl->getLocation(),
5657 diag::err_operator_new_delete_too_few_parameters)
5658 << FnDecl->getDeclName();
5659
5660 // Check the the first parameter type is not dependent.
5661 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5662 if (FirstParamType->isDependentType())
5663 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5664 << FnDecl->getDeclName() << ExpectedFirstParamType;
5665
5666 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005667 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005668 ExpectedFirstParamType)
5669 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5670 << FnDecl->getDeclName() << ExpectedFirstParamType;
5671
5672 return false;
5673}
5674
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005675static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005676CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005677 // C++ [basic.stc.dynamic.allocation]p1:
5678 // A program is ill-formed if an allocation function is declared in a
5679 // namespace scope other than global scope or declared static in global
5680 // scope.
5681 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5682 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005683
5684 CanQualType SizeTy =
5685 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5686
5687 // C++ [basic.stc.dynamic.allocation]p1:
5688 // The return type shall be void*. The first parameter shall have type
5689 // std::size_t.
5690 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5691 SizeTy,
5692 diag::err_operator_new_dependent_param_type,
5693 diag::err_operator_new_param_type))
5694 return true;
5695
5696 // C++ [basic.stc.dynamic.allocation]p1:
5697 // The first parameter shall not have an associated default argument.
5698 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005699 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005700 diag::err_operator_new_default_arg)
5701 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5702
5703 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005704}
5705
5706static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005707CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5708 // C++ [basic.stc.dynamic.deallocation]p1:
5709 // A program is ill-formed if deallocation functions are declared in a
5710 // namespace scope other than global scope or declared static in global
5711 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005712 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5713 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005714
5715 // C++ [basic.stc.dynamic.deallocation]p2:
5716 // Each deallocation function shall return void and its first parameter
5717 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005718 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5719 SemaRef.Context.VoidPtrTy,
5720 diag::err_operator_delete_dependent_param_type,
5721 diag::err_operator_delete_param_type))
5722 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005723
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005724 return false;
5725}
5726
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005727/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5728/// of this overloaded operator is well-formed. If so, returns false;
5729/// otherwise, emits appropriate diagnostics and returns true.
5730bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005731 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005732 "Expected an overloaded operator declaration");
5733
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005734 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5735
Mike Stump1eb44332009-09-09 15:08:12 +00005736 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005737 // The allocation and deallocation functions, operator new,
5738 // operator new[], operator delete and operator delete[], are
5739 // described completely in 3.7.3. The attributes and restrictions
5740 // found in the rest of this subclause do not apply to them unless
5741 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005742 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005743 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005744
Anders Carlssona3ccda52009-12-12 00:26:23 +00005745 if (Op == OO_New || Op == OO_Array_New)
5746 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005747
5748 // C++ [over.oper]p6:
5749 // An operator function shall either be a non-static member
5750 // function or be a non-member function and have at least one
5751 // parameter whose type is a class, a reference to a class, an
5752 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005753 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5754 if (MethodDecl->isStatic())
5755 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005756 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005757 } else {
5758 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005759 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5760 ParamEnd = FnDecl->param_end();
5761 Param != ParamEnd; ++Param) {
5762 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005763 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5764 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005765 ClassOrEnumParam = true;
5766 break;
5767 }
5768 }
5769
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005770 if (!ClassOrEnumParam)
5771 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005772 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005773 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005774 }
5775
5776 // C++ [over.oper]p8:
5777 // An operator function cannot have default arguments (8.3.6),
5778 // except where explicitly stated below.
5779 //
Mike Stump1eb44332009-09-09 15:08:12 +00005780 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005781 // (C++ [over.call]p1).
5782 if (Op != OO_Call) {
5783 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5784 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005785 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005786 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005787 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005788 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005789 }
5790 }
5791
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005792 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5793 { false, false, false }
5794#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5795 , { Unary, Binary, MemberOnly }
5796#include "clang/Basic/OperatorKinds.def"
5797 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005798
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005799 bool CanBeUnaryOperator = OperatorUses[Op][0];
5800 bool CanBeBinaryOperator = OperatorUses[Op][1];
5801 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005802
5803 // C++ [over.oper]p8:
5804 // [...] Operator functions cannot have more or fewer parameters
5805 // than the number required for the corresponding operator, as
5806 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005807 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005808 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005809 if (Op != OO_Call &&
5810 ((NumParams == 1 && !CanBeUnaryOperator) ||
5811 (NumParams == 2 && !CanBeBinaryOperator) ||
5812 (NumParams < 1) || (NumParams > 2))) {
5813 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005814 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005815 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005816 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005817 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005818 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005819 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005820 assert(CanBeBinaryOperator &&
5821 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005822 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005823 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005824
Chris Lattner416e46f2008-11-21 07:57:12 +00005825 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005826 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005827 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005828
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005829 // Overloaded operators other than operator() cannot be variadic.
5830 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005831 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005832 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005833 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005834 }
5835
5836 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005837 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5838 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005839 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005840 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005841 }
5842
5843 // C++ [over.inc]p1:
5844 // The user-defined function called operator++ implements the
5845 // prefix and postfix ++ operator. If this function is a member
5846 // function with no parameters, or a non-member function with one
5847 // parameter of class or enumeration type, it defines the prefix
5848 // increment operator ++ for objects of that type. If the function
5849 // is a member function with one parameter (which shall be of type
5850 // int) or a non-member function with two parameters (the second
5851 // of which shall be of type int), it defines the postfix
5852 // increment operator ++ for objects of that type.
5853 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5854 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5855 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005856 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005857 ParamIsInt = BT->getKind() == BuiltinType::Int;
5858
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005859 if (!ParamIsInt)
5860 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005861 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005862 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005863 }
5864
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005865 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005866}
Chris Lattner5a003a42008-12-17 07:09:26 +00005867
Sean Hunta6c058d2010-01-13 09:01:02 +00005868/// CheckLiteralOperatorDeclaration - Check whether the declaration
5869/// of this literal operator function is well-formed. If so, returns
5870/// false; otherwise, emits appropriate diagnostics and returns true.
5871bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5872 DeclContext *DC = FnDecl->getDeclContext();
5873 Decl::Kind Kind = DC->getDeclKind();
5874 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5875 Kind != Decl::LinkageSpec) {
5876 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5877 << FnDecl->getDeclName();
5878 return true;
5879 }
5880
5881 bool Valid = false;
5882
Sean Hunt216c2782010-04-07 23:11:06 +00005883 // template <char...> type operator "" name() is the only valid template
5884 // signature, and the only valid signature with no parameters.
5885 if (FnDecl->param_size() == 0) {
5886 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5887 // Must have only one template parameter
5888 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5889 if (Params->size() == 1) {
5890 NonTypeTemplateParmDecl *PmDecl =
5891 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005892
Sean Hunt216c2782010-04-07 23:11:06 +00005893 // The template parameter must be a char parameter pack.
5894 // FIXME: This test will always fail because non-type parameter packs
5895 // have not been implemented.
5896 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5897 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5898 Valid = true;
5899 }
5900 }
5901 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005902 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005903 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5904
Sean Hunta6c058d2010-01-13 09:01:02 +00005905 QualType T = (*Param)->getType();
5906
Sean Hunt30019c02010-04-07 22:57:35 +00005907 // unsigned long long int, long double, and any character type are allowed
5908 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005909 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5910 Context.hasSameType(T, Context.LongDoubleTy) ||
5911 Context.hasSameType(T, Context.CharTy) ||
5912 Context.hasSameType(T, Context.WCharTy) ||
5913 Context.hasSameType(T, Context.Char16Ty) ||
5914 Context.hasSameType(T, Context.Char32Ty)) {
5915 if (++Param == FnDecl->param_end())
5916 Valid = true;
5917 goto FinishedParams;
5918 }
5919
Sean Hunt30019c02010-04-07 22:57:35 +00005920 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005921 const PointerType *PT = T->getAs<PointerType>();
5922 if (!PT)
5923 goto FinishedParams;
5924 T = PT->getPointeeType();
5925 if (!T.isConstQualified())
5926 goto FinishedParams;
5927 T = T.getUnqualifiedType();
5928
5929 // Move on to the second parameter;
5930 ++Param;
5931
5932 // If there is no second parameter, the first must be a const char *
5933 if (Param == FnDecl->param_end()) {
5934 if (Context.hasSameType(T, Context.CharTy))
5935 Valid = true;
5936 goto FinishedParams;
5937 }
5938
5939 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5940 // are allowed as the first parameter to a two-parameter function
5941 if (!(Context.hasSameType(T, Context.CharTy) ||
5942 Context.hasSameType(T, Context.WCharTy) ||
5943 Context.hasSameType(T, Context.Char16Ty) ||
5944 Context.hasSameType(T, Context.Char32Ty)))
5945 goto FinishedParams;
5946
5947 // The second and final parameter must be an std::size_t
5948 T = (*Param)->getType().getUnqualifiedType();
5949 if (Context.hasSameType(T, Context.getSizeType()) &&
5950 ++Param == FnDecl->param_end())
5951 Valid = true;
5952 }
5953
5954 // FIXME: This diagnostic is absolutely terrible.
5955FinishedParams:
5956 if (!Valid) {
5957 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5958 << FnDecl->getDeclName();
5959 return true;
5960 }
5961
5962 return false;
5963}
5964
Douglas Gregor074149e2009-01-05 19:45:36 +00005965/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5966/// linkage specification, including the language and (if present)
5967/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5968/// the location of the language string literal, which is provided
5969/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5970/// the '{' brace. Otherwise, this linkage specification does not
5971/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00005972Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5973 SourceLocation LangLoc,
5974 llvm::StringRef Lang,
5975 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005976 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005977 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005978 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005979 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005980 Language = LinkageSpecDecl::lang_cxx;
5981 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005982 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00005983 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005984 }
Mike Stump1eb44332009-09-09 15:08:12 +00005985
Chris Lattnercc98eac2008-12-17 07:13:27 +00005986 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005987
Douglas Gregor074149e2009-01-05 19:45:36 +00005988 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005989 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005990 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005991 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005992 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00005993 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005994}
5995
Abramo Bagnara35f9a192010-07-30 16:47:02 +00005996/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00005997/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5998/// valid, it's the position of the closing '}' brace in a linkage
5999/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006000Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6001 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006002 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006003 if (LinkageSpec)
6004 PopDeclContext();
6005 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006006}
6007
Douglas Gregord308e622009-05-18 20:51:54 +00006008/// \brief Perform semantic analysis for the variable declaration that
6009/// occurs within a C++ catch clause, returning the newly-created
6010/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006011VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006012 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006013 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006014 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006015 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006016 QualType ExDeclType = TInfo->getType();
6017
Sebastian Redl4b07b292008-12-22 19:15:10 +00006018 // Arrays and functions decay.
6019 if (ExDeclType->isArrayType())
6020 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6021 else if (ExDeclType->isFunctionType())
6022 ExDeclType = Context.getPointerType(ExDeclType);
6023
6024 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6025 // The exception-declaration shall not denote a pointer or reference to an
6026 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006027 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006028 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006029 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006030 Invalid = true;
6031 }
Douglas Gregord308e622009-05-18 20:51:54 +00006032
Douglas Gregora2762912010-03-08 01:47:36 +00006033 // GCC allows catching pointers and references to incomplete types
6034 // as an extension; so do we, but we warn by default.
6035
Sebastian Redl4b07b292008-12-22 19:15:10 +00006036 QualType BaseType = ExDeclType;
6037 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006038 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006039 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006040 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006041 BaseType = Ptr->getPointeeType();
6042 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006043 DK = diag::ext_catch_incomplete_ptr;
6044 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006045 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006046 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006047 BaseType = Ref->getPointeeType();
6048 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006049 DK = diag::ext_catch_incomplete_ref;
6050 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006051 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006052 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006053 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6054 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006055 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006056
Mike Stump1eb44332009-09-09 15:08:12 +00006057 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006058 RequireNonAbstractType(Loc, ExDeclType,
6059 diag::err_abstract_type_in_decl,
6060 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006061 Invalid = true;
6062
John McCall5a180392010-07-24 00:37:23 +00006063 // Only the non-fragile NeXT runtime currently supports C++ catches
6064 // of ObjC types, and no runtime supports catching ObjC types by value.
6065 if (!Invalid && getLangOptions().ObjC1) {
6066 QualType T = ExDeclType;
6067 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6068 T = RT->getPointeeType();
6069
6070 if (T->isObjCObjectType()) {
6071 Diag(Loc, diag::err_objc_object_catch);
6072 Invalid = true;
6073 } else if (T->isObjCObjectPointerType()) {
6074 if (!getLangOptions().NeXTRuntime) {
6075 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6076 Invalid = true;
6077 } else if (!getLangOptions().ObjCNonFragileABI) {
6078 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6079 Invalid = true;
6080 }
6081 }
6082 }
6083
Mike Stump1eb44332009-09-09 15:08:12 +00006084 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006085 Name, ExDeclType, TInfo, SC_None,
6086 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006087 ExDecl->setExceptionVariable(true);
6088
Douglas Gregor6d182892010-03-05 23:38:39 +00006089 if (!Invalid) {
6090 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6091 // C++ [except.handle]p16:
6092 // The object declared in an exception-declaration or, if the
6093 // exception-declaration does not specify a name, a temporary (12.2) is
6094 // copy-initialized (8.5) from the exception object. [...]
6095 // The object is destroyed when the handler exits, after the destruction
6096 // of any automatic objects initialized within the handler.
6097 //
6098 // We just pretend to initialize the object with itself, then make sure
6099 // it can be destroyed later.
6100 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6101 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006102 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006103 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6104 SourceLocation());
6105 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006106 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006107 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006108 if (Result.isInvalid())
6109 Invalid = true;
6110 else
6111 FinalizeVarWithDestructor(ExDecl, RecordTy);
6112 }
6113 }
6114
Douglas Gregord308e622009-05-18 20:51:54 +00006115 if (Invalid)
6116 ExDecl->setInvalidDecl();
6117
6118 return ExDecl;
6119}
6120
6121/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6122/// handler.
John McCalld226f652010-08-21 09:40:31 +00006123Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006124 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6125 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006126
6127 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006128 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006129 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006130 LookupOrdinaryName,
6131 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006132 // The scope should be freshly made just for us. There is just no way
6133 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006134 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006135 if (PrevDecl->isTemplateParameter()) {
6136 // Maybe we will complain about the shadowed template parameter.
6137 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006138 }
6139 }
6140
Chris Lattnereaaebc72009-04-25 08:06:05 +00006141 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006142 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6143 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006144 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006145 }
6146
Douglas Gregor83cb9422010-09-09 17:09:21 +00006147 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006148 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006149 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006150
Chris Lattnereaaebc72009-04-25 08:06:05 +00006151 if (Invalid)
6152 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006153
Sebastian Redl4b07b292008-12-22 19:15:10 +00006154 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006155 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006156 PushOnScopeChains(ExDecl, S);
6157 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006158 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006159
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006160 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006161 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006162}
Anders Carlssonfb311762009-03-14 00:25:26 +00006163
John McCalld226f652010-08-21 09:40:31 +00006164Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006165 Expr *AssertExpr,
6166 Expr *AssertMessageExpr_) {
6167 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006168
Anders Carlssonc3082412009-03-14 00:33:21 +00006169 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6170 llvm::APSInt Value(32);
6171 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6172 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6173 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006174 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006175 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006176
Anders Carlssonc3082412009-03-14 00:33:21 +00006177 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006178 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006179 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006180 }
6181 }
Mike Stump1eb44332009-09-09 15:08:12 +00006182
Douglas Gregor399ad972010-12-15 23:55:21 +00006183 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6184 return 0;
6185
Mike Stump1eb44332009-09-09 15:08:12 +00006186 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006187 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006188
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006189 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006190 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006191}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006192
Douglas Gregor1d869352010-04-07 16:53:43 +00006193/// \brief Perform semantic analysis of the given friend type declaration.
6194///
6195/// \returns A friend declaration that.
6196FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6197 TypeSourceInfo *TSInfo) {
6198 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6199
6200 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006201 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006202
Douglas Gregor06245bf2010-04-07 17:57:12 +00006203 if (!getLangOptions().CPlusPlus0x) {
6204 // C++03 [class.friend]p2:
6205 // An elaborated-type-specifier shall be used in a friend declaration
6206 // for a class.*
6207 //
6208 // * The class-key of the elaborated-type-specifier is required.
6209 if (!ActiveTemplateInstantiations.empty()) {
6210 // Do not complain about the form of friend template types during
6211 // template instantiation; we will already have complained when the
6212 // template was declared.
6213 } else if (!T->isElaboratedTypeSpecifier()) {
6214 // If we evaluated the type to a record type, suggest putting
6215 // a tag in front.
6216 if (const RecordType *RT = T->getAs<RecordType>()) {
6217 RecordDecl *RD = RT->getDecl();
6218
6219 std::string InsertionText = std::string(" ") + RD->getKindName();
6220
6221 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6222 << (unsigned) RD->getTagKind()
6223 << T
6224 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6225 InsertionText);
6226 } else {
6227 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6228 << T
6229 << SourceRange(FriendLoc, TypeRange.getEnd());
6230 }
6231 } else if (T->getAs<EnumType>()) {
6232 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006233 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006234 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006235 }
6236 }
6237
Douglas Gregor06245bf2010-04-07 17:57:12 +00006238 // C++0x [class.friend]p3:
6239 // If the type specifier in a friend declaration designates a (possibly
6240 // cv-qualified) class type, that class is declared as a friend; otherwise,
6241 // the friend declaration is ignored.
6242
6243 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6244 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006245
6246 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6247}
6248
John McCall9a34edb2010-10-19 01:40:49 +00006249/// Handle a friend tag declaration where the scope specifier was
6250/// templated.
6251Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6252 unsigned TagSpec, SourceLocation TagLoc,
6253 CXXScopeSpec &SS,
6254 IdentifierInfo *Name, SourceLocation NameLoc,
6255 AttributeList *Attr,
6256 MultiTemplateParamsArg TempParamLists) {
6257 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6258
6259 bool isExplicitSpecialization = false;
6260 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6261 bool Invalid = false;
6262
6263 if (TemplateParameterList *TemplateParams
6264 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6265 TempParamLists.get(),
6266 TempParamLists.size(),
6267 /*friend*/ true,
6268 isExplicitSpecialization,
6269 Invalid)) {
6270 --NumMatchedTemplateParamLists;
6271
6272 if (TemplateParams->size() > 0) {
6273 // This is a declaration of a class template.
6274 if (Invalid)
6275 return 0;
6276
6277 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6278 SS, Name, NameLoc, Attr,
6279 TemplateParams, AS_public).take();
6280 } else {
6281 // The "template<>" header is extraneous.
6282 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6283 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6284 isExplicitSpecialization = true;
6285 }
6286 }
6287
6288 if (Invalid) return 0;
6289
6290 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6291
6292 bool isAllExplicitSpecializations = true;
6293 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6294 if (TempParamLists.get()[I]->size()) {
6295 isAllExplicitSpecializations = false;
6296 break;
6297 }
6298 }
6299
6300 // FIXME: don't ignore attributes.
6301
6302 // If it's explicit specializations all the way down, just forget
6303 // about the template header and build an appropriate non-templated
6304 // friend. TODO: for source fidelity, remember the headers.
6305 if (isAllExplicitSpecializations) {
6306 ElaboratedTypeKeyword Keyword
6307 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6308 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6309 TagLoc, SS.getRange(), NameLoc);
6310 if (T.isNull())
6311 return 0;
6312
6313 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6314 if (isa<DependentNameType>(T)) {
6315 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6316 TL.setKeywordLoc(TagLoc);
6317 TL.setQualifierRange(SS.getRange());
6318 TL.setNameLoc(NameLoc);
6319 } else {
6320 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6321 TL.setKeywordLoc(TagLoc);
6322 TL.setQualifierRange(SS.getRange());
6323 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6324 }
6325
6326 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6327 TSI, FriendLoc);
6328 Friend->setAccess(AS_public);
6329 CurContext->addDecl(Friend);
6330 return Friend;
6331 }
6332
6333 // Handle the case of a templated-scope friend class. e.g.
6334 // template <class T> class A<T>::B;
6335 // FIXME: we don't support these right now.
6336 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6337 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6338 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6339 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6340 TL.setKeywordLoc(TagLoc);
6341 TL.setQualifierRange(SS.getRange());
6342 TL.setNameLoc(NameLoc);
6343
6344 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6345 TSI, FriendLoc);
6346 Friend->setAccess(AS_public);
6347 Friend->setUnsupportedFriend(true);
6348 CurContext->addDecl(Friend);
6349 return Friend;
6350}
6351
6352
John McCalldd4a3b02009-09-16 22:47:08 +00006353/// Handle a friend type declaration. This works in tandem with
6354/// ActOnTag.
6355///
6356/// Notes on friend class templates:
6357///
6358/// We generally treat friend class declarations as if they were
6359/// declaring a class. So, for example, the elaborated type specifier
6360/// in a friend declaration is required to obey the restrictions of a
6361/// class-head (i.e. no typedefs in the scope chain), template
6362/// parameters are required to match up with simple template-ids, &c.
6363/// However, unlike when declaring a template specialization, it's
6364/// okay to refer to a template specialization without an empty
6365/// template parameter declaration, e.g.
6366/// friend class A<T>::B<unsigned>;
6367/// We permit this as a special case; if there are any template
6368/// parameters present at all, require proper matching, i.e.
6369/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006370Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006371 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006372 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006373
6374 assert(DS.isFriendSpecified());
6375 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6376
John McCalldd4a3b02009-09-16 22:47:08 +00006377 // Try to convert the decl specifier to a type. This works for
6378 // friend templates because ActOnTag never produces a ClassTemplateDecl
6379 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006380 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006381 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6382 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006383 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006384 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006385
Douglas Gregor6ccab972010-12-16 01:14:37 +00006386 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6387 return 0;
6388
John McCalldd4a3b02009-09-16 22:47:08 +00006389 // This is definitely an error in C++98. It's probably meant to
6390 // be forbidden in C++0x, too, but the specification is just
6391 // poorly written.
6392 //
6393 // The problem is with declarations like the following:
6394 // template <T> friend A<T>::foo;
6395 // where deciding whether a class C is a friend or not now hinges
6396 // on whether there exists an instantiation of A that causes
6397 // 'foo' to equal C. There are restrictions on class-heads
6398 // (which we declare (by fiat) elaborated friend declarations to
6399 // be) that makes this tractable.
6400 //
6401 // FIXME: handle "template <> friend class A<T>;", which
6402 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006403 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006404 Diag(Loc, diag::err_tagless_friend_type_template)
6405 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006406 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006407 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006408
John McCall02cace72009-08-28 07:59:38 +00006409 // C++98 [class.friend]p1: A friend of a class is a function
6410 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006411 // This is fixed in DR77, which just barely didn't make the C++03
6412 // deadline. It's also a very silly restriction that seriously
6413 // affects inner classes and which nobody else seems to implement;
6414 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006415 //
6416 // But note that we could warn about it: it's always useless to
6417 // friend one of your own members (it's not, however, worthless to
6418 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006419
John McCalldd4a3b02009-09-16 22:47:08 +00006420 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006421 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006422 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006423 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006424 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006425 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006426 DS.getFriendSpecLoc());
6427 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006428 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6429
6430 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006431 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006432
John McCalldd4a3b02009-09-16 22:47:08 +00006433 D->setAccess(AS_public);
6434 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006435
John McCalld226f652010-08-21 09:40:31 +00006436 return D;
John McCall02cace72009-08-28 07:59:38 +00006437}
6438
John McCall337ec3d2010-10-12 23:13:28 +00006439Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6440 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006441 const DeclSpec &DS = D.getDeclSpec();
6442
6443 assert(DS.isFriendSpecified());
6444 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6445
6446 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006447 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6448 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006449
6450 // C++ [class.friend]p1
6451 // A friend of a class is a function or class....
6452 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006453 // It *doesn't* see through dependent types, which is correct
6454 // according to [temp.arg.type]p3:
6455 // If a declaration acquires a function type through a
6456 // type dependent on a template-parameter and this causes
6457 // a declaration that does not use the syntactic form of a
6458 // function declarator to have a function type, the program
6459 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006460 if (!T->isFunctionType()) {
6461 Diag(Loc, diag::err_unexpected_friend);
6462
6463 // It might be worthwhile to try to recover by creating an
6464 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006465 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006466 }
6467
6468 // C++ [namespace.memdef]p3
6469 // - If a friend declaration in a non-local class first declares a
6470 // class or function, the friend class or function is a member
6471 // of the innermost enclosing namespace.
6472 // - The name of the friend is not found by simple name lookup
6473 // until a matching declaration is provided in that namespace
6474 // scope (either before or after the class declaration granting
6475 // friendship).
6476 // - If a friend function is called, its name may be found by the
6477 // name lookup that considers functions from namespaces and
6478 // classes associated with the types of the function arguments.
6479 // - When looking for a prior declaration of a class or a function
6480 // declared as a friend, scopes outside the innermost enclosing
6481 // namespace scope are not considered.
6482
John McCall337ec3d2010-10-12 23:13:28 +00006483 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006484 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6485 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006486 assert(Name);
6487
Douglas Gregor6ccab972010-12-16 01:14:37 +00006488 // Check for unexpanded parameter packs.
6489 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6490 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6491 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6492 return 0;
6493
John McCall67d1a672009-08-06 02:15:43 +00006494 // The context we found the declaration in, or in which we should
6495 // create the declaration.
6496 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006497 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006498 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006499 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006500
John McCall337ec3d2010-10-12 23:13:28 +00006501 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006502
John McCall337ec3d2010-10-12 23:13:28 +00006503 // There are four cases here.
6504 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006505 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006506 // there as appropriate.
6507 // Recover from invalid scope qualifiers as if they just weren't there.
6508 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006509 // C++0x [namespace.memdef]p3:
6510 // If the name in a friend declaration is neither qualified nor
6511 // a template-id and the declaration is a function or an
6512 // elaborated-type-specifier, the lookup to determine whether
6513 // the entity has been previously declared shall not consider
6514 // any scopes outside the innermost enclosing namespace.
6515 // C++0x [class.friend]p11:
6516 // If a friend declaration appears in a local class and the name
6517 // specified is an unqualified name, a prior declaration is
6518 // looked up without considering scopes that are outside the
6519 // innermost enclosing non-class scope. For a friend function
6520 // declaration, if there is no prior declaration, the program is
6521 // ill-formed.
6522 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006523 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006524
John McCall29ae6e52010-10-13 05:45:15 +00006525 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006526 DC = CurContext;
6527 while (true) {
6528 // Skip class contexts. If someone can cite chapter and verse
6529 // for this behavior, that would be nice --- it's what GCC and
6530 // EDG do, and it seems like a reasonable intent, but the spec
6531 // really only says that checks for unqualified existing
6532 // declarations should stop at the nearest enclosing namespace,
6533 // not that they should only consider the nearest enclosing
6534 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006535 while (DC->isRecord())
6536 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006537
John McCall68263142009-11-18 22:49:29 +00006538 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006539
6540 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006541 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006542 break;
John McCall29ae6e52010-10-13 05:45:15 +00006543
John McCall8a407372010-10-14 22:22:28 +00006544 if (isTemplateId) {
6545 if (isa<TranslationUnitDecl>(DC)) break;
6546 } else {
6547 if (DC->isFileContext()) break;
6548 }
John McCall67d1a672009-08-06 02:15:43 +00006549 DC = DC->getParent();
6550 }
6551
6552 // C++ [class.friend]p1: A friend of a class is a function or
6553 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006554 // C++0x changes this for both friend types and functions.
6555 // Most C++ 98 compilers do seem to give an error here, so
6556 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006557 if (!Previous.empty() && DC->Equals(CurContext)
6558 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006559 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006560
John McCall380aaa42010-10-13 06:22:15 +00006561 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006562
John McCall337ec3d2010-10-12 23:13:28 +00006563 // - There's a non-dependent scope specifier, in which case we
6564 // compute it and do a previous lookup there for a function
6565 // or function template.
6566 } else if (!SS.getScopeRep()->isDependent()) {
6567 DC = computeDeclContext(SS);
6568 if (!DC) return 0;
6569
6570 if (RequireCompleteDeclContext(SS, DC)) return 0;
6571
6572 LookupQualifiedName(Previous, DC);
6573
6574 // Ignore things found implicitly in the wrong scope.
6575 // TODO: better diagnostics for this case. Suggesting the right
6576 // qualified scope would be nice...
6577 LookupResult::Filter F = Previous.makeFilter();
6578 while (F.hasNext()) {
6579 NamedDecl *D = F.next();
6580 if (!DC->InEnclosingNamespaceSetOf(
6581 D->getDeclContext()->getRedeclContext()))
6582 F.erase();
6583 }
6584 F.done();
6585
6586 if (Previous.empty()) {
6587 D.setInvalidType();
6588 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6589 return 0;
6590 }
6591
6592 // C++ [class.friend]p1: A friend of a class is a function or
6593 // class that is not a member of the class . . .
6594 if (DC->Equals(CurContext))
6595 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6596
6597 // - There's a scope specifier that does not match any template
6598 // parameter lists, in which case we use some arbitrary context,
6599 // create a method or method template, and wait for instantiation.
6600 // - There's a scope specifier that does match some template
6601 // parameter lists, which we don't handle right now.
6602 } else {
6603 DC = CurContext;
6604 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006605 }
6606
John McCall29ae6e52010-10-13 05:45:15 +00006607 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006608 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006609 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6610 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6611 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006612 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006613 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6614 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006615 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006616 }
John McCall67d1a672009-08-06 02:15:43 +00006617 }
6618
Douglas Gregor182ddf02009-09-28 00:08:27 +00006619 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006620 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006621 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006622 IsDefinition,
6623 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006624 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006625
Douglas Gregor182ddf02009-09-28 00:08:27 +00006626 assert(ND->getDeclContext() == DC);
6627 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006628
John McCallab88d972009-08-31 22:39:49 +00006629 // Add the function declaration to the appropriate lookup tables,
6630 // adjusting the redeclarations list as necessary. We don't
6631 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006632 //
John McCallab88d972009-08-31 22:39:49 +00006633 // Also update the scope-based lookup if the target context's
6634 // lookup context is in lexical scope.
6635 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006636 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006637 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006638 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006639 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006640 }
John McCall02cace72009-08-28 07:59:38 +00006641
6642 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006643 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006644 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006645 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006646 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006647
John McCall337ec3d2010-10-12 23:13:28 +00006648 if (ND->isInvalidDecl())
6649 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006650 else {
6651 FunctionDecl *FD;
6652 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6653 FD = FTD->getTemplatedDecl();
6654 else
6655 FD = cast<FunctionDecl>(ND);
6656
6657 // Mark templated-scope function declarations as unsupported.
6658 if (FD->getNumTemplateParameterLists())
6659 FrD->setUnsupportedFriend(true);
6660 }
John McCall337ec3d2010-10-12 23:13:28 +00006661
John McCalld226f652010-08-21 09:40:31 +00006662 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006663}
6664
John McCalld226f652010-08-21 09:40:31 +00006665void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6666 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006667
Sebastian Redl50de12f2009-03-24 22:27:57 +00006668 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6669 if (!Fn) {
6670 Diag(DelLoc, diag::err_deleted_non_function);
6671 return;
6672 }
6673 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6674 Diag(DelLoc, diag::err_deleted_decl_not_first);
6675 Diag(Prev->getLocation(), diag::note_previous_declaration);
6676 // If the declaration wasn't the first, we delete the function anyway for
6677 // recovery.
6678 }
6679 Fn->setDeleted();
6680}
Sebastian Redl13e88542009-04-27 21:33:24 +00006681
6682static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6683 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6684 ++CI) {
6685 Stmt *SubStmt = *CI;
6686 if (!SubStmt)
6687 continue;
6688 if (isa<ReturnStmt>(SubStmt))
6689 Self.Diag(SubStmt->getSourceRange().getBegin(),
6690 diag::err_return_in_constructor_handler);
6691 if (!isa<Expr>(SubStmt))
6692 SearchForReturnInStmt(Self, SubStmt);
6693 }
6694}
6695
6696void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6697 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6698 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6699 SearchForReturnInStmt(*this, Handler);
6700 }
6701}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006702
Mike Stump1eb44332009-09-09 15:08:12 +00006703bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006704 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006705 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6706 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006707
Chandler Carruth73857792010-02-15 11:53:20 +00006708 if (Context.hasSameType(NewTy, OldTy) ||
6709 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006710 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006711
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006712 // Check if the return types are covariant
6713 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006714
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006715 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006716 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6717 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006718 NewClassTy = NewPT->getPointeeType();
6719 OldClassTy = OldPT->getPointeeType();
6720 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006721 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6722 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6723 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6724 NewClassTy = NewRT->getPointeeType();
6725 OldClassTy = OldRT->getPointeeType();
6726 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006727 }
6728 }
Mike Stump1eb44332009-09-09 15:08:12 +00006729
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006730 // The return types aren't either both pointers or references to a class type.
6731 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006732 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006733 diag::err_different_return_type_for_overriding_virtual_function)
6734 << New->getDeclName() << NewTy << OldTy;
6735 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006736
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006737 return true;
6738 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006739
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006740 // C++ [class.virtual]p6:
6741 // If the return type of D::f differs from the return type of B::f, the
6742 // class type in the return type of D::f shall be complete at the point of
6743 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006744 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6745 if (!RT->isBeingDefined() &&
6746 RequireCompleteType(New->getLocation(), NewClassTy,
6747 PDiag(diag::err_covariant_return_incomplete)
6748 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006749 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006750 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006751
Douglas Gregora4923eb2009-11-16 21:35:15 +00006752 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006753 // Check if the new class derives from the old class.
6754 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6755 Diag(New->getLocation(),
6756 diag::err_covariant_return_not_derived)
6757 << New->getDeclName() << NewTy << OldTy;
6758 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6759 return true;
6760 }
Mike Stump1eb44332009-09-09 15:08:12 +00006761
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006762 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006763 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006764 diag::err_covariant_return_inaccessible_base,
6765 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6766 // FIXME: Should this point to the return type?
6767 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006768 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6769 return true;
6770 }
6771 }
Mike Stump1eb44332009-09-09 15:08:12 +00006772
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006773 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006774 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006775 Diag(New->getLocation(),
6776 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006777 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006778 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6779 return true;
6780 };
Mike Stump1eb44332009-09-09 15:08:12 +00006781
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006782
6783 // The new class type must have the same or less qualifiers as the old type.
6784 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6785 Diag(New->getLocation(),
6786 diag::err_covariant_return_type_class_type_more_qualified)
6787 << New->getDeclName() << NewTy << OldTy;
6788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6789 return true;
6790 };
Mike Stump1eb44332009-09-09 15:08:12 +00006791
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006792 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006793}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006794
Sean Huntbbd37c62009-11-21 08:43:09 +00006795bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6796 const CXXMethodDecl *Old)
6797{
6798 if (Old->hasAttr<FinalAttr>()) {
6799 Diag(New->getLocation(), diag::err_final_function_overridden)
6800 << New->getDeclName();
6801 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6802 return true;
6803 }
6804
6805 return false;
6806}
6807
Douglas Gregor4ba31362009-12-01 17:24:26 +00006808/// \brief Mark the given method pure.
6809///
6810/// \param Method the method to be marked pure.
6811///
6812/// \param InitRange the source range that covers the "0" initializer.
6813bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6814 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6815 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006816 return false;
6817 }
6818
6819 if (!Method->isInvalidDecl())
6820 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6821 << Method->getDeclName() << InitRange;
6822 return true;
6823}
6824
John McCall731ad842009-12-19 09:28:58 +00006825/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6826/// an initializer for the out-of-line declaration 'Dcl'. The scope
6827/// is a fresh scope pushed for just this purpose.
6828///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006829/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6830/// static data member of class X, names should be looked up in the scope of
6831/// class X.
John McCalld226f652010-08-21 09:40:31 +00006832void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006833 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006834 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006835
John McCall731ad842009-12-19 09:28:58 +00006836 // We should only get called for declarations with scope specifiers, like:
6837 // int foo::bar;
6838 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006839 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006840}
6841
6842/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006843/// initializer for the out-of-line declaration 'D'.
6844void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006845 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006846 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006847
John McCall731ad842009-12-19 09:28:58 +00006848 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006849 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006850}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006851
6852/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6853/// C++ if/switch/while/for statement.
6854/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006855DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006856 // C++ 6.4p2:
6857 // The declarator shall not specify a function or an array.
6858 // The type-specifier-seq shall not contain typedef and shall not declare a
6859 // new class or enumeration.
6860 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6861 "Parser allowed 'typedef' as storage class of condition decl.");
6862
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006863 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006864 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6865 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006866
6867 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6868 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6869 // would be created and CXXConditionDeclExpr wants a VarDecl.
6870 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6871 << D.getSourceRange();
6872 return DeclResult();
6873 } else if (OwnedTag && OwnedTag->isDefinition()) {
6874 // The type-specifier-seq shall not declare a new class or enumeration.
6875 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6876 }
6877
John McCalld226f652010-08-21 09:40:31 +00006878 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006879 if (!Dcl)
6880 return DeclResult();
6881
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006882 return Dcl;
6883}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006884
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006885void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6886 bool DefinitionRequired) {
6887 // Ignore any vtable uses in unevaluated operands or for classes that do
6888 // not have a vtable.
6889 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6890 CurContext->isDependentContext() ||
6891 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006892 return;
6893
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006894 // Try to insert this class into the map.
6895 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6896 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6897 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6898 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006899 // If we already had an entry, check to see if we are promoting this vtable
6900 // to required a definition. If so, we need to reappend to the VTableUses
6901 // list, since we may have already processed the first entry.
6902 if (DefinitionRequired && !Pos.first->second) {
6903 Pos.first->second = true;
6904 } else {
6905 // Otherwise, we can early exit.
6906 return;
6907 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006908 }
6909
6910 // Local classes need to have their virtual members marked
6911 // immediately. For all other classes, we mark their virtual members
6912 // at the end of the translation unit.
6913 if (Class->isLocalClass())
6914 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006915 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006916 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006917}
6918
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006919bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006920 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006921 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00006922
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006923 // Note: The VTableUses vector could grow as a result of marking
6924 // the members of a class as "used", so we check the size each
6925 // time through the loop and prefer indices (with are stable) to
6926 // iterators (which are not).
6927 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006928 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006929 if (!Class)
6930 continue;
6931
6932 SourceLocation Loc = VTableUses[I].second;
6933
6934 // If this class has a key function, but that key function is
6935 // defined in another translation unit, we don't need to emit the
6936 // vtable even though we're using it.
6937 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006938 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006939 switch (KeyFunction->getTemplateSpecializationKind()) {
6940 case TSK_Undeclared:
6941 case TSK_ExplicitSpecialization:
6942 case TSK_ExplicitInstantiationDeclaration:
6943 // The key function is in another translation unit.
6944 continue;
6945
6946 case TSK_ExplicitInstantiationDefinition:
6947 case TSK_ImplicitInstantiation:
6948 // We will be instantiating the key function.
6949 break;
6950 }
6951 } else if (!KeyFunction) {
6952 // If we have a class with no key function that is the subject
6953 // of an explicit instantiation declaration, suppress the
6954 // vtable; it will live with the explicit instantiation
6955 // definition.
6956 bool IsExplicitInstantiationDeclaration
6957 = Class->getTemplateSpecializationKind()
6958 == TSK_ExplicitInstantiationDeclaration;
6959 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6960 REnd = Class->redecls_end();
6961 R != REnd; ++R) {
6962 TemplateSpecializationKind TSK
6963 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6964 if (TSK == TSK_ExplicitInstantiationDeclaration)
6965 IsExplicitInstantiationDeclaration = true;
6966 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6967 IsExplicitInstantiationDeclaration = false;
6968 break;
6969 }
6970 }
6971
6972 if (IsExplicitInstantiationDeclaration)
6973 continue;
6974 }
6975
6976 // Mark all of the virtual members of this class as referenced, so
6977 // that we can build a vtable. Then, tell the AST consumer that a
6978 // vtable for this class is required.
6979 MarkVirtualMembersReferenced(Loc, Class);
6980 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6981 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6982
6983 // Optionally warn if we're emitting a weak vtable.
6984 if (Class->getLinkage() == ExternalLinkage &&
6985 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006986 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006987 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6988 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006989 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006990 VTableUses.clear();
6991
Anders Carlssond6a637f2009-12-07 08:24:59 +00006992 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006993}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006994
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006995void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6996 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006997 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6998 e = RD->method_end(); i != e; ++i) {
6999 CXXMethodDecl *MD = *i;
7000
7001 // C++ [basic.def.odr]p2:
7002 // [...] A virtual member function is used if it is not pure. [...]
7003 if (MD->isVirtual() && !MD->isPure())
7004 MarkDeclarationReferenced(Loc, MD);
7005 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007006
7007 // Only classes that have virtual bases need a VTT.
7008 if (RD->getNumVBases() == 0)
7009 return;
7010
7011 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7012 e = RD->bases_end(); i != e; ++i) {
7013 const CXXRecordDecl *Base =
7014 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007015 if (Base->getNumVBases() == 0)
7016 continue;
7017 MarkVirtualMembersReferenced(Loc, Base);
7018 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007019}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007020
7021/// SetIvarInitializers - This routine builds initialization ASTs for the
7022/// Objective-C implementation whose ivars need be initialized.
7023void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7024 if (!getLangOptions().CPlusPlus)
7025 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007026 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007027 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7028 CollectIvarsToConstructOrDestruct(OID, ivars);
7029 if (ivars.empty())
7030 return;
7031 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7032 for (unsigned i = 0; i < ivars.size(); i++) {
7033 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007034 if (Field->isInvalidDecl())
7035 continue;
7036
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007037 CXXBaseOrMemberInitializer *Member;
7038 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7039 InitializationKind InitKind =
7040 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7041
7042 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007043 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007044 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007045 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007046 // Note, MemberInit could actually come back empty if no initialization
7047 // is required (e.g., because it would call a trivial default constructor)
7048 if (!MemberInit.get() || MemberInit.isInvalid())
7049 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007050
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007051 Member =
7052 new (Context) CXXBaseOrMemberInitializer(Context,
7053 Field, SourceLocation(),
7054 SourceLocation(),
7055 MemberInit.takeAs<Expr>(),
7056 SourceLocation());
7057 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007058
7059 // Be sure that the destructor is accessible and is marked as referenced.
7060 if (const RecordType *RecordTy
7061 = Context.getBaseElementType(Field->getType())
7062 ->getAs<RecordType>()) {
7063 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007064 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007065 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7066 CheckDestructorAccess(Field->getLocation(), Destructor,
7067 PDiag(diag::err_access_dtor_ivar)
7068 << Context.getBaseElementType(Field->getType()));
7069 }
7070 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007071 }
7072 ObjCImplementation->setIvarInitializers(Context,
7073 AllToInit.data(), AllToInit.size());
7074 }
7075}