blob: 58f656c1454a58ed58877e4a172011086b8515ac [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;
John McCall7502c1d2011-02-13 04:07:26 +000066 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000068 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000069 }
70
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitDeclRefExpr - Visit a reference to a declaration, to
72 /// determine whether this declaration can be used in the default
73 /// argument expression.
74 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000075 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000076 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
77 // C++ [dcl.fct.default]p9
78 // Default arguments are evaluated each time the function is
79 // called. The order of evaluation of function arguments is
80 // unspecified. Consequently, parameters of a function shall not
81 // be used in default argument expressions, even if they are not
82 // evaluated. Parameters of a function declared before a default
83 // argument expression are in scope and can hide namespace and
84 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000085 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000087 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000088 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000089 // C++ [dcl.fct.default]p7
90 // Local variables shall not be used in default argument
91 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000092 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000093 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000096 }
Chris Lattner8123a952008-04-10 02:22:51 +000097
Douglas Gregor3996f232008-11-04 13:41:56 +000098 return false;
99 }
Chris Lattner9e979552008-04-12 23:52:44 +0000100
Douglas Gregor796da182008-11-04 14:32:21 +0000101 /// VisitCXXThisExpr - Visit a C++ "this" expression.
102 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
103 // C++ [dcl.fct.default]p8:
104 // The keyword this shall not be used in a default argument of a
105 // member function.
106 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000107 diag::err_param_default_argument_references_this)
108 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000109 }
Chris Lattner8123a952008-04-10 02:22:51 +0000110}
111
Anders Carlssoned961f92009-08-25 02:29:20 +0000112bool
John McCall9ae2f072010-08-23 23:25:46 +0000113Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000114 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000115 if (RequireCompleteType(Param->getLocation(), Param->getType(),
116 diag::err_typecheck_decl_incomplete_type)) {
117 Param->setInvalidDecl();
118 return true;
119 }
120
Anders Carlssoned961f92009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
128 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000131 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000132 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000133 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000137
John McCallb4eb64d2010-10-08 02:01:28 +0000138 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000139 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 // Okay: add the default argument to the parameter
142 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000144 // We have already instantiated this parameter; provide each of the
145 // instantiations with the uninstantiated default argument.
146 UnparsedDefaultArgInstantiationsMap::iterator InstPos
147 = UnparsedDefaultArgInstantiations.find(Param);
148 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
149 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
150 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
151
152 // We're done tracking this parameter's instantiations.
153 UnparsedDefaultArgInstantiations.erase(InstPos);
154 }
155
Anders Carlsson9351c172009-08-25 03:18:48 +0000156 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000157}
158
Chris Lattner8123a952008-04-10 02:22:51 +0000159/// ActOnParamDefaultArgument - Check whether the default argument
160/// provided for a function parameter is well-formed. If so, attach it
161/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000162void
John McCalld226f652010-08-21 09:40:31 +0000163Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000164 Expr *DefaultArg) {
165 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000166 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000167
John McCalld226f652010-08-21 09:40:31 +0000168 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000169 UnparsedDefaultArgLocs.erase(Param);
170
Chris Lattner3d1cee32008-04-08 05:04:30 +0000171 // Default arguments are only permitted in C++
172 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000173 Diag(EqualLoc, diag::err_param_default_argument)
174 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000175 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176 return;
177 }
178
Douglas Gregor6f526752010-12-16 08:48:57 +0000179 // Check for unexpanded parameter packs.
180 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
181 Param->setInvalidDecl();
182 return;
183 }
184
Anders Carlsson66e30672009-08-25 01:02:06 +0000185 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000186 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
187 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000188 Param->setInvalidDecl();
189 return;
190 }
Mike Stump1eb44332009-09-09 15:08:12 +0000191
John McCall9ae2f072010-08-23 23:25:46 +0000192 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000193}
194
Douglas Gregor61366e92008-12-24 00:01:03 +0000195/// ActOnParamUnparsedDefaultArgument - We've seen a default
196/// argument for a function parameter, but we can't parse it yet
197/// because we're inside a class definition. Note that this default
198/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000199void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000200 SourceLocation EqualLoc,
201 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000202 if (!param)
203 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
John McCalld226f652010-08-21 09:40:31 +0000205 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000206 if (Param)
207 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Anders Carlsson5e300d12009-06-12 16:51:40 +0000209 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000210}
211
Douglas Gregor72b505b2008-12-16 21:30:33 +0000212/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
213/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000214void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000215 if (!param)
216 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000217
John McCalld226f652010-08-21 09:40:31 +0000218 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Anders Carlsson5e300d12009-06-12 16:51:40 +0000220 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Anders Carlsson5e300d12009-06-12 16:51:40 +0000222 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223}
224
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000225/// CheckExtraCXXDefaultArguments - Check for any extra default
226/// arguments in the declarator, which is not a function declaration
227/// or definition and therefore is not permitted to have default
228/// arguments. This routine should be invoked for every declarator
229/// that is not a function declaration or definition.
230void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
231 // C++ [dcl.fct.default]p3
232 // A default argument expression shall be specified only in the
233 // parameter-declaration-clause of a function declaration or in a
234 // template-parameter (14.1). It shall not be specified for a
235 // parameter pack. If it is specified in a
236 // parameter-declaration-clause, it shall not occur within a
237 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000238 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000239 DeclaratorChunk &chunk = D.getTypeObject(i);
240 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000241 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
242 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000243 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000244 if (Param->hasUnparsedDefaultArg()) {
245 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
248 delete Toks;
249 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000250 } else if (Param->getDefaultArg()) {
251 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
252 << Param->getDefaultArg()->getSourceRange();
253 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000254 }
255 }
256 }
257 }
258}
259
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260// MergeCXXFunctionDecl - Merge two declarations of the same C++
261// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000262// type. Subroutine of MergeFunctionDecl. Returns true if there was an
263// error, false otherwise.
264bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
265 bool Invalid = false;
266
Chris Lattner3d1cee32008-04-08 05:04:30 +0000267 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 // For non-template functions, default arguments can be added in
269 // later declarations of a function in the same
270 // scope. Declarations in different scopes have completely
271 // distinct sets of default arguments. That is, declarations in
272 // inner scopes do not acquire default arguments from
273 // declarations in outer scopes, and vice versa. In a given
274 // function declaration, all parameters subsequent to a
275 // parameter with a default argument shall have default
276 // arguments supplied in this or previous declarations. A
277 // default argument shall not be redefined by a later
278 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000279 //
280 // C++ [dcl.fct.default]p6:
281 // Except for member functions of class templates, the default arguments
282 // in a member function definition that appears outside of the class
283 // definition are added to the set of default arguments provided by the
284 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000285 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
286 ParmVarDecl *OldParam = Old->getParamDecl(p);
287 ParmVarDecl *NewParam = New->getParamDecl(p);
288
Douglas Gregor6cc15182009-09-11 18:44:32 +0000289 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000290 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
291 // hint here. Alternatively, we could walk the type-source information
292 // for NewParam to find the last source location in the type... but it
293 // isn't worth the effort right now. This is the kind of test case that
294 // is hard to get right:
295
296 // int f(int);
297 // void g(int (*fp)(int) = f);
298 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000299 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000300 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000301 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000302
303 // Look for the function declaration where the default argument was
304 // actually written, which may be a declaration prior to Old.
305 for (FunctionDecl *Older = Old->getPreviousDeclaration();
306 Older; Older = Older->getPreviousDeclaration()) {
307 if (!Older->getParamDecl(p)->hasDefaultArg())
308 break;
309
310 OldParam = Older->getParamDecl(p);
311 }
312
313 Diag(OldParam->getLocation(), diag::note_previous_definition)
314 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000315 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000316 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000317 // Merge the old default argument into the new parameter.
318 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000319 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000320 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000321 if (OldParam->hasUninstantiatedDefaultArg())
322 NewParam->setUninstantiatedDefaultArg(
323 OldParam->getUninstantiatedDefaultArg());
324 else
John McCall3d6c1782010-05-04 01:53:42 +0000325 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000326 } else if (NewParam->hasDefaultArg()) {
327 if (New->getDescribedFunctionTemplate()) {
328 // Paragraph 4, quoted above, only applies to non-template functions.
329 Diag(NewParam->getLocation(),
330 diag::err_param_default_argument_template_redecl)
331 << NewParam->getDefaultArgRange();
332 Diag(Old->getLocation(), diag::note_template_prev_declaration)
333 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000334 } else if (New->getTemplateSpecializationKind()
335 != TSK_ImplicitInstantiation &&
336 New->getTemplateSpecializationKind() != TSK_Undeclared) {
337 // C++ [temp.expr.spec]p21:
338 // Default function arguments shall not be specified in a declaration
339 // or a definition for one of the following explicit specializations:
340 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000341 // - the explicit specialization of a member function template;
342 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000343 // template where the class template specialization to which the
344 // member function specialization belongs is implicitly
345 // instantiated.
346 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
347 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
348 << New->getDeclName()
349 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000350 } else if (New->getDeclContext()->isDependentContext()) {
351 // C++ [dcl.fct.default]p6 (DR217):
352 // Default arguments for a member function of a class template shall
353 // be specified on the initial declaration of the member function
354 // within the class template.
355 //
356 // Reading the tea leaves a bit in DR217 and its reference to DR205
357 // leads me to the conclusion that one cannot add default function
358 // arguments for an out-of-line definition of a member function of a
359 // dependent type.
360 int WhichKind = 2;
361 if (CXXRecordDecl *Record
362 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
363 if (Record->getDescribedClassTemplate())
364 WhichKind = 0;
365 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
366 WhichKind = 1;
367 else
368 WhichKind = 2;
369 }
370
371 Diag(NewParam->getLocation(),
372 diag::err_param_default_argument_member_template_redecl)
373 << WhichKind
374 << NewParam->getDefaultArgRange();
375 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376 }
377 }
378
Douglas Gregore13ad832010-02-12 07:32:17 +0000379 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000380 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000381
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383}
384
385/// CheckCXXDefaultArguments - Verify that the default arguments for a
386/// function declaration are well-formed according to C++
387/// [dcl.fct.default].
388void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
389 unsigned NumParams = FD->getNumParams();
390 unsigned p;
391
392 // Find first parameter with a default argument
393 for (p = 0; p < NumParams; ++p) {
394 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000395 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 break;
397 }
398
399 // C++ [dcl.fct.default]p4:
400 // In a given function declaration, all parameters
401 // subsequent to a parameter with a default argument shall
402 // have default arguments supplied in this or previous
403 // declarations. A default argument shall not be redefined
404 // by a later declaration (not even to the same value).
405 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000406 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000408 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000409 if (Param->isInvalidDecl())
410 /* We already complained about this parameter. */;
411 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000412 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000413 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000414 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 else
Mike Stump1eb44332009-09-09 15:08:12 +0000416 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000417 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner3d1cee32008-04-08 05:04:30 +0000419 LastMissingDefaultArg = p;
420 }
421 }
422
423 if (LastMissingDefaultArg > 0) {
424 // Some default arguments were missing. Clear out all of the
425 // default arguments up to (and including) the last missing
426 // default argument, so that we leave the function parameters
427 // in a semantically valid state.
428 for (p = 0; p <= LastMissingDefaultArg; ++p) {
429 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000430 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000431 Param->setDefaultArg(0);
432 }
433 }
434 }
435}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000436
Douglas Gregorb48fe382008-10-31 09:07:45 +0000437/// isCurrentClassName - Determine whether the identifier II is the
438/// name of the class type currently being defined. In the case of
439/// nested classes, this will only return true if II is the name of
440/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000441bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
442 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000443 assert(getLangOptions().CPlusPlus && "No class names in C!");
444
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000445 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000446 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000447 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000448 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
449 } else
450 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
451
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000452 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000453 return &II == CurDecl->getIdentifier();
454 else
455 return false;
456}
457
Mike Stump1eb44332009-09-09 15:08:12 +0000458/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000459///
460/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
461/// and returns NULL otherwise.
462CXXBaseSpecifier *
463Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
464 SourceRange SpecifierRange,
465 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000466 TypeSourceInfo *TInfo,
467 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000468 QualType BaseType = TInfo->getType();
469
Douglas Gregor2943aed2009-03-03 04:44:36 +0000470 // C++ [class.union]p1:
471 // A union shall not have base classes.
472 if (Class->isUnion()) {
473 Diag(Class->getLocation(), diag::err_base_clause_on_union)
474 << SpecifierRange;
475 return 0;
476 }
477
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000478 if (EllipsisLoc.isValid() &&
479 !TInfo->getType()->containsUnexpandedParameterPack()) {
480 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
481 << TInfo->getTypeLoc().getSourceRange();
482 EllipsisLoc = SourceLocation();
483 }
484
Douglas Gregor2943aed2009-03-03 04:44:36 +0000485 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000486 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000487 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000488 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000489
490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000491
492 // Base specifiers must be record types.
493 if (!BaseType->isRecordType()) {
494 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
495 return 0;
496 }
497
498 // C++ [class.union]p1:
499 // A union shall not be used as a base class.
500 if (BaseType->isUnionType()) {
501 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
502 return 0;
503 }
504
505 // C++ [class.derived]p2:
506 // The class-name in a base-specifier shall not be an incompletely
507 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000508 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000509 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000510 << SpecifierRange)) {
511 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000512 return 0;
John McCall572fc622010-08-17 07:23:57 +0000513 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000514
Eli Friedman1d954f62009-08-15 21:55:26 +0000515 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000516 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000517 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000518 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000519 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000520 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
521 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000522
Anders Carlssondfc2f102011-01-22 17:51:53 +0000523 // C++ [class.derived]p2:
524 // If a class is marked with the class-virt-specifier final and it appears
525 // as a base-type-specifier in a base-clause (10 class.derived), the program
526 // is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000527 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000528 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
529 << CXXBaseDecl->getDeclName();
530 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
531 << CXXBaseDecl->getDeclName();
532 return 0;
533 }
534
John McCall572fc622010-08-17 07:23:57 +0000535 if (BaseDecl->isInvalidDecl())
536 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000537
538 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000539 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000540 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000541 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000542}
543
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000544/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
545/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000546/// example:
547/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000548/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000549BaseResult
John McCalld226f652010-08-21 09:40:31 +0000550Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000551 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000552 ParsedType basetype, SourceLocation BaseLoc,
553 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000554 if (!classdecl)
555 return true;
556
Douglas Gregor40808ce2009-03-09 23:48:35 +0000557 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000558 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000559 if (!Class)
560 return true;
561
Nick Lewycky56062202010-07-26 16:56:01 +0000562 TypeSourceInfo *TInfo = 0;
563 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000564
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000565 if (EllipsisLoc.isInvalid() &&
566 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000567 UPPC_BaseType))
568 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000569
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000571 Virtual, Access, TInfo,
572 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000576}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000577
Douglas Gregor2943aed2009-03-03 04:44:36 +0000578/// \brief Performs the actual work of attaching the given base class
579/// specifiers to a C++ class.
580bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
581 unsigned NumBases) {
582 if (NumBases == 0)
583 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000584
585 // Used to keep track of which base types we have already seen, so
586 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000587 // that the key is always the unqualified canonical type of the base
588 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000589 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
590
591 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000592 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000594 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000595 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000597 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000598 if (!Class->hasObjectMember()) {
599 if (const RecordType *FDTTy =
600 NewBaseType.getTypePtr()->getAs<RecordType>())
601 if (FDTTy->getDecl()->hasObjectMember())
602 Class->setHasObjectMember(true);
603 }
604
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605 if (KnownBaseTypes[NewBaseType]) {
606 // C++ [class.mi]p3:
607 // A class shall not be specified as a direct base class of a
608 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000610 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000611 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000612 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613
614 // Delete the duplicate base class specifier; we're going to
615 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000616 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617
618 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000619 } else {
620 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 KnownBaseTypes[NewBaseType] = Bases[idx];
622 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000623 }
624 }
625
626 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000627 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the remaining (good) base class specifiers, since their
630 // data has been copied into the CXXRecordDecl.
631 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000632 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633
634 return Invalid;
635}
636
637/// ActOnBaseSpecifiers - Attach the given base specifiers to the
638/// class, after checking whether there are any duplicate base
639/// classes.
John McCalld226f652010-08-21 09:40:31 +0000640void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000641 unsigned NumBases) {
642 if (!ClassDecl || !Bases || !NumBases)
643 return;
644
645 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000646 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000647 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000648}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000649
John McCall3cb0ebd2010-03-10 03:28:59 +0000650static CXXRecordDecl *GetClassForType(QualType T) {
651 if (const RecordType *RT = T->getAs<RecordType>())
652 return cast<CXXRecordDecl>(RT->getDecl());
653 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
654 return ICT->getDecl();
655 else
656 return 0;
657}
658
Douglas Gregora8f32e02009-10-06 17:59:45 +0000659/// \brief Determine whether the type \p Derived is a C++ class that is
660/// derived from the type \p Base.
661bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
662 if (!getLangOptions().CPlusPlus)
663 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000664
665 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
666 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000667 return false;
668
John McCall3cb0ebd2010-03-10 03:28:59 +0000669 CXXRecordDecl *BaseRD = GetClassForType(Base);
670 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000671 return false;
672
John McCall86ff3082010-02-04 22:26:26 +0000673 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
674 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000675}
676
677/// \brief Determine whether the type \p Derived is a C++ class that is
678/// derived from the type \p Base.
679bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
680 if (!getLangOptions().CPlusPlus)
681 return false;
682
John McCall3cb0ebd2010-03-10 03:28:59 +0000683 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
684 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000685 return false;
686
John McCall3cb0ebd2010-03-10 03:28:59 +0000687 CXXRecordDecl *BaseRD = GetClassForType(Base);
688 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000689 return false;
690
Douglas Gregora8f32e02009-10-06 17:59:45 +0000691 return DerivedRD->isDerivedFrom(BaseRD, Paths);
692}
693
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000694void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000695 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000696 assert(BasePathArray.empty() && "Base path array must be empty!");
697 assert(Paths.isRecordingPaths() && "Must record paths!");
698
699 const CXXBasePath &Path = Paths.front();
700
701 // We first go backward and check if we have a virtual base.
702 // FIXME: It would be better if CXXBasePath had the base specifier for
703 // the nearest virtual base.
704 unsigned Start = 0;
705 for (unsigned I = Path.size(); I != 0; --I) {
706 if (Path[I - 1].Base->isVirtual()) {
707 Start = I - 1;
708 break;
709 }
710 }
711
712 // Now add all bases.
713 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000714 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000715}
716
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000717/// \brief Determine whether the given base path includes a virtual
718/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000719bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
720 for (CXXCastPath::const_iterator B = BasePath.begin(),
721 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000722 B != BEnd; ++B)
723 if ((*B)->isVirtual())
724 return true;
725
726 return false;
727}
728
Douglas Gregora8f32e02009-10-06 17:59:45 +0000729/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
730/// conversion (where Derived and Base are class types) is
731/// well-formed, meaning that the conversion is unambiguous (and
732/// that all of the base classes are accessible). Returns true
733/// and emits a diagnostic if the code is ill-formed, returns false
734/// otherwise. Loc is the location where this routine should point to
735/// if there is an error, and Range is the source range to highlight
736/// if there is an error.
737bool
738Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000739 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000740 unsigned AmbigiousBaseConvID,
741 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000742 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000743 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000744 // First, determine whether the path from Derived to Base is
745 // ambiguous. This is slightly more expensive than checking whether
746 // the Derived to Base conversion exists, because here we need to
747 // explore multiple paths to determine if there is an ambiguity.
748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
749 /*DetectVirtual=*/false);
750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
751 assert(DerivationOkay &&
752 "Can only be used with a derived-to-base conversion");
753 (void)DerivationOkay;
754
755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000756 if (InaccessibleBaseID) {
757 // Check that the base class can be accessed.
758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
759 InaccessibleBaseID)) {
760 case AR_inaccessible:
761 return true;
762 case AR_accessible:
763 case AR_dependent:
764 case AR_delayed:
765 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000766 }
John McCall6b2accb2010-02-10 09:31:12 +0000767 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000768
769 // Build a base path if necessary.
770 if (BasePath)
771 BuildBasePathArray(Paths, *BasePath);
772 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000773 }
774
775 // We know that the derived-to-base conversion is ambiguous, and
776 // we're going to produce a diagnostic. Perform the derived-to-base
777 // search just one more time to compute all of the possible paths so
778 // that we can print them out. This is more expensive than any of
779 // the previous derived-to-base checks we've done, but at this point
780 // performance isn't as much of an issue.
781 Paths.clear();
782 Paths.setRecordingPaths(true);
783 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
784 assert(StillOkay && "Can only be used with a derived-to-base conversion");
785 (void)StillOkay;
786
787 // Build up a textual representation of the ambiguous paths, e.g.,
788 // D -> B -> A, that will be used to illustrate the ambiguous
789 // conversions in the diagnostic. We only print one of the paths
790 // to each base class subobject.
791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
792
793 Diag(Loc, AmbigiousBaseConvID)
794 << Derived << Base << PathDisplayStr << Range << Name;
795 return true;
796}
797
798bool
799Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000800 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000801 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000802 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000803 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000804 IgnoreAccess ? 0
805 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000807 Loc, Range, DeclarationName(),
808 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000809}
810
811
812/// @brief Builds a string representing ambiguous paths from a
813/// specific derived class to different subobjects of the same base
814/// class.
815///
816/// This function builds a string that can be used in error messages
817/// to show the different paths that one can take through the
818/// inheritance hierarchy to go from the derived class to different
819/// subobjects of a base class. The result looks something like this:
820/// @code
821/// struct D -> struct B -> struct A
822/// struct D -> struct C -> struct A
823/// @endcode
824std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
825 std::string PathDisplayStr;
826 std::set<unsigned> DisplayedPaths;
827 for (CXXBasePaths::paths_iterator Path = Paths.begin();
828 Path != Paths.end(); ++Path) {
829 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
830 // We haven't displayed a path to this particular base
831 // class subobject yet.
832 PathDisplayStr += "\n ";
833 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
834 for (CXXBasePath::const_iterator Element = Path->begin();
835 Element != Path->end(); ++Element)
836 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
837 }
838 }
839
840 return PathDisplayStr;
841}
842
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000843//===----------------------------------------------------------------------===//
844// C++ class member Handling
845//===----------------------------------------------------------------------===//
846
Abramo Bagnara6206d532010-06-05 05:09:32 +0000847/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000848Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
849 SourceLocation ASLoc,
850 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000851 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000852 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000853 ASLoc, ColonLoc);
854 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000855 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000856}
857
Anders Carlsson9e682d92011-01-20 05:57:14 +0000858/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000859void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000860 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
861 if (!MD || !MD->isVirtual())
862 return;
863
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000864 if (MD->isDependentContext())
865 return;
866
Anders Carlsson9e682d92011-01-20 05:57:14 +0000867 // C++0x [class.virtual]p3:
868 // If a virtual function is marked with the virt-specifier override and does
869 // not override a member function of a base class,
870 // the program is ill-formed.
871 bool HasOverriddenMethods =
872 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000873 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000874 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000875 diag::err_function_marked_override_not_overriding)
876 << MD->getDeclName();
877 return;
878 }
Anders Carlssonaa23d282011-01-22 22:23:37 +0000879
880 // C++0x [class.derived]p8:
881 // In a class definition marked with the class-virt-specifier explicit,
882 // if a virtual member function that is neither implicitly-declared nor a
883 // destructor overrides a member function of a base class and it is not
884 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000885 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
886 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlssonaa23d282011-01-22 22:23:37 +0000887 llvm::SmallVector<const CXXMethodDecl*, 4>
888 OverriddenMethods(MD->begin_overridden_methods(),
889 MD->end_overridden_methods());
890
891 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
892 << MD->getDeclName()
893 << (unsigned)OverriddenMethods.size();
894
895 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
896 Diag(OverriddenMethods[I]->getLocation(),
897 diag::note_overridden_virtual_function);
898 }
Anders Carlsson9e682d92011-01-20 05:57:14 +0000899}
900
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000901/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
902/// function overrides a virtual member function marked 'final', according to
903/// C++0x [class.virtual]p3.
904bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
905 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000906 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000907 return false;
908
909 Diag(New->getLocation(), diag::err_final_function_overridden)
910 << New->getDeclName();
911 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
912 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000913}
914
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000915/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
916/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
917/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000918/// any.
John McCalld226f652010-08-21 09:40:31 +0000919Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000920Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000921 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000922 ExprTy *BW, const VirtSpecifiers &VS,
923 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000924 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000925 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000926 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
927 DeclarationName Name = NameInfo.getName();
928 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000929
930 // For anonymous bitfields, the location should point to the type.
931 if (Loc.isInvalid())
932 Loc = D.getSourceRange().getBegin();
933
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000934 Expr *BitWidth = static_cast<Expr*>(BW);
935 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000936
John McCall4bde1e12010-06-04 08:34:12 +0000937 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000938 assert(!DS.isFriendSpecified());
939
John McCall4bde1e12010-06-04 08:34:12 +0000940 bool isFunc = false;
941 if (D.isFunctionDeclarator())
942 isFunc = true;
943 else if (D.getNumTypeObjects() == 0 &&
944 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000945 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000946 isFunc = TDType->isFunctionType();
947 }
948
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949 // C++ 9.2p6: A member shall not be declared to have automatic storage
950 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000951 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
952 // data members and cannot be applied to names declared const or static,
953 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000954 switch (DS.getStorageClassSpec()) {
955 case DeclSpec::SCS_unspecified:
956 case DeclSpec::SCS_typedef:
957 case DeclSpec::SCS_static:
958 // FALL THROUGH.
959 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000960 case DeclSpec::SCS_mutable:
961 if (isFunc) {
962 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000963 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000964 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000965 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Sebastian Redla11f42f2008-11-17 23:24:37 +0000967 // FIXME: It would be nicer if the keyword was ignored only for this
968 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000969 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000970 }
971 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000972 default:
973 if (DS.getStorageClassSpecLoc().isValid())
974 Diag(DS.getStorageClassSpecLoc(),
975 diag::err_storageclass_invalid_for_member);
976 else
977 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
978 D.getMutableDeclSpec().ClearStorageClassSpecs();
979 }
980
Sebastian Redl669d5d72008-11-14 23:42:31 +0000981 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
982 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000983 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000984
985 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000986 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000987 CXXScopeSpec &SS = D.getCXXScopeSpec();
988
989
990 if (SS.isSet() && !SS.isInvalid()) {
991 // The user provided a superfluous scope specifier inside a class
992 // definition:
993 //
994 // class X {
995 // int X::member;
996 // };
997 DeclContext *DC = 0;
998 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
999 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1000 << Name << FixItHint::CreateRemoval(SS.getRange());
1001 else
1002 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1003 << Name << SS.getRange();
1004
1005 SS.clear();
1006 }
1007
Douglas Gregor37b372b2009-08-20 22:52:58 +00001008 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001009 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001010 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1011 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001012 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001013 } else {
John McCalld226f652010-08-21 09:40:31 +00001014 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001015 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001016 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001017 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001018
1019 // Non-instance-fields can't have a bitfield.
1020 if (BitWidth) {
1021 if (Member->isInvalidDecl()) {
1022 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001023 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001024 // C++ 9.6p3: A bit-field shall not be a static member.
1025 // "static member 'A' cannot be a bit-field"
1026 Diag(Loc, diag::err_static_not_bitfield)
1027 << Name << BitWidth->getSourceRange();
1028 } else if (isa<TypedefDecl>(Member)) {
1029 // "typedef member 'x' cannot be a bit-field"
1030 Diag(Loc, diag::err_typedef_not_bitfield)
1031 << Name << BitWidth->getSourceRange();
1032 } else {
1033 // A function typedef ("typedef int f(); f a;").
1034 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1035 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001036 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001037 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner8b963ef2009-03-05 23:01:03 +00001040 BitWidth = 0;
1041 Member->setInvalidDecl();
1042 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001043
1044 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregor37b372b2009-08-20 22:52:58 +00001046 // If we have declared a member function template, set the access of the
1047 // templated declaration as well.
1048 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1049 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001050 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001051
Anders Carlssonaae5af22011-01-20 04:34:22 +00001052 if (VS.isOverrideSpecified()) {
1053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1054 if (!MD || !MD->isVirtual()) {
1055 Diag(Member->getLocStart(),
1056 diag::override_keyword_only_allowed_on_virtual_member_functions)
1057 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001058 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001059 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001060 }
1061 if (VS.isFinalSpecified()) {
1062 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1063 if (!MD || !MD->isVirtual()) {
1064 Diag(Member->getLocStart(),
1065 diag::override_keyword_only_allowed_on_virtual_member_functions)
1066 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001067 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001068 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001069 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001070
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001071 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001072
Douglas Gregor10bd3682008-11-17 22:58:34 +00001073 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001074
Douglas Gregor021c3b32009-03-11 23:00:04 +00001075 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001076 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001077 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001078 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001079
John McCallb25b2952011-02-15 07:12:36 +00001080 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001081 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001082 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001083}
1084
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001085/// \brief Find the direct and/or virtual base specifiers that
1086/// correspond to the given base type, for use in base initialization
1087/// within a constructor.
1088static bool FindBaseInitializer(Sema &SemaRef,
1089 CXXRecordDecl *ClassDecl,
1090 QualType BaseType,
1091 const CXXBaseSpecifier *&DirectBaseSpec,
1092 const CXXBaseSpecifier *&VirtualBaseSpec) {
1093 // First, check for a direct base class.
1094 DirectBaseSpec = 0;
1095 for (CXXRecordDecl::base_class_const_iterator Base
1096 = ClassDecl->bases_begin();
1097 Base != ClassDecl->bases_end(); ++Base) {
1098 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1099 // We found a direct base of this type. That's what we're
1100 // initializing.
1101 DirectBaseSpec = &*Base;
1102 break;
1103 }
1104 }
1105
1106 // Check for a virtual base class.
1107 // FIXME: We might be able to short-circuit this if we know in advance that
1108 // there are no virtual bases.
1109 VirtualBaseSpec = 0;
1110 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1111 // We haven't found a base yet; search the class hierarchy for a
1112 // virtual base class.
1113 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1114 /*DetectVirtual=*/false);
1115 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1116 BaseType, Paths)) {
1117 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1118 Path != Paths.end(); ++Path) {
1119 if (Path->back().Base->isVirtual()) {
1120 VirtualBaseSpec = Path->back().Base;
1121 break;
1122 }
1123 }
1124 }
1125 }
1126
1127 return DirectBaseSpec || VirtualBaseSpec;
1128}
1129
Douglas Gregor7ad83902008-11-05 04:29:56 +00001130/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001131MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001132Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001133 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001134 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001135 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001136 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001137 SourceLocation IdLoc,
1138 SourceLocation LParenLoc,
1139 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001140 SourceLocation RParenLoc,
1141 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001142 if (!ConstructorD)
1143 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001145 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
1147 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001148 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001149 if (!Constructor) {
1150 // The user wrote a constructor initializer on a function that is
1151 // not a C++ constructor. Ignore the error for now, because we may
1152 // have more member initializers coming; we'll diagnose it just
1153 // once in ActOnMemInitializers.
1154 return true;
1155 }
1156
1157 CXXRecordDecl *ClassDecl = Constructor->getParent();
1158
1159 // C++ [class.base.init]p2:
1160 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001161 // constructor's class and, if not found in that scope, are looked
1162 // up in the scope containing the constructor's definition.
1163 // [Note: if the constructor's class contains a member with the
1164 // same name as a direct or virtual base class of the class, a
1165 // mem-initializer-id naming the member or base class and composed
1166 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001167 // mem-initializer-id for the hidden base class may be specified
1168 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001169 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001170 // Look for a member, first.
1171 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001172 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001173 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001174 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001175 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001176
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001177 if (Member) {
1178 if (EllipsisLoc.isValid())
1179 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1180 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1181
Francois Pichet00eb3f92010-12-04 09:14:42 +00001182 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001183 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001184 }
1185
Francois Pichet00eb3f92010-12-04 09:14:42 +00001186 // Handle anonymous union case.
1187 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001188 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1189 if (EllipsisLoc.isValid())
1190 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1191 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1192
Francois Pichet00eb3f92010-12-04 09:14:42 +00001193 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1194 NumArgs, IdLoc,
1195 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001196 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001197 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001198 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001199 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001200 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001201 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001202
1203 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001204 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001205 } else {
1206 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1207 LookupParsedName(R, S, &SS);
1208
1209 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1210 if (!TyD) {
1211 if (R.isAmbiguous()) return true;
1212
John McCallfd225442010-04-09 19:01:14 +00001213 // We don't want access-control diagnostics here.
1214 R.suppressDiagnostics();
1215
Douglas Gregor7a886e12010-01-19 06:46:48 +00001216 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1217 bool NotUnknownSpecialization = false;
1218 DeclContext *DC = computeDeclContext(SS, false);
1219 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1220 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1221
1222 if (!NotUnknownSpecialization) {
1223 // When the scope specifier can refer to a member of an unknown
1224 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001225 BaseType = CheckTypenameType(ETK_None,
1226 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001227 *MemberOrBase, SourceLocation(),
1228 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001229 if (BaseType.isNull())
1230 return true;
1231
Douglas Gregor7a886e12010-01-19 06:46:48 +00001232 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001233 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001234 }
1235 }
1236
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001237 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001238 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001239 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1240 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001241 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001242 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001243 // We have found a non-static data member with a similar
1244 // name to what was typed; complain and initialize that
1245 // member.
1246 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1247 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001248 << FixItHint::CreateReplacement(R.getNameLoc(),
1249 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001250 Diag(Member->getLocation(), diag::note_previous_decl)
1251 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001252
1253 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1254 LParenLoc, RParenLoc);
1255 }
1256 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1257 const CXXBaseSpecifier *DirectBaseSpec;
1258 const CXXBaseSpecifier *VirtualBaseSpec;
1259 if (FindBaseInitializer(*this, ClassDecl,
1260 Context.getTypeDeclType(Type),
1261 DirectBaseSpec, VirtualBaseSpec)) {
1262 // We have found a direct or virtual base class with a
1263 // similar name to what was typed; complain and initialize
1264 // that base class.
1265 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1266 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001267 << FixItHint::CreateReplacement(R.getNameLoc(),
1268 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001269
1270 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1271 : VirtualBaseSpec;
1272 Diag(BaseSpec->getSourceRange().getBegin(),
1273 diag::note_base_class_specified_here)
1274 << BaseSpec->getType()
1275 << BaseSpec->getSourceRange();
1276
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001277 TyD = Type;
1278 }
1279 }
1280 }
1281
Douglas Gregor7a886e12010-01-19 06:46:48 +00001282 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001283 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1284 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1285 return true;
1286 }
John McCall2b194412009-12-21 10:41:20 +00001287 }
1288
Douglas Gregor7a886e12010-01-19 06:46:48 +00001289 if (BaseType.isNull()) {
1290 BaseType = Context.getTypeDeclType(TyD);
1291 if (SS.isSet()) {
1292 NestedNameSpecifier *Qualifier =
1293 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001294
Douglas Gregor7a886e12010-01-19 06:46:48 +00001295 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001296 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001297 }
John McCall2b194412009-12-21 10:41:20 +00001298 }
1299 }
Mike Stump1eb44332009-09-09 15:08:12 +00001300
John McCalla93c9342009-12-07 02:54:59 +00001301 if (!TInfo)
1302 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001303
John McCalla93c9342009-12-07 02:54:59 +00001304 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001305 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001306}
1307
John McCallb4190042009-11-04 23:02:40 +00001308/// Checks an initializer expression for use of uninitialized fields, such as
1309/// containing the field that is being initialized. Returns true if there is an
1310/// uninitialized field was used an updates the SourceLocation parameter; false
1311/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001312static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001313 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001314 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001315 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1316
Nick Lewycky43ad1822010-06-15 07:32:55 +00001317 if (isa<CallExpr>(S)) {
1318 // Do not descend into function calls or constructors, as the use
1319 // of an uninitialized field may be valid. One would have to inspect
1320 // the contents of the function/ctor to determine if it is safe or not.
1321 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1322 // may be safe, depending on what the function/ctor does.
1323 return false;
1324 }
1325 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1326 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001327
1328 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1329 // The member expression points to a static data member.
1330 assert(VD->isStaticDataMember() &&
1331 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001332 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001333 return false;
1334 }
1335
1336 if (isa<EnumConstantDecl>(RhsField)) {
1337 // The member expression points to an enum.
1338 return false;
1339 }
1340
John McCallb4190042009-11-04 23:02:40 +00001341 if (RhsField == LhsField) {
1342 // Initializing a field with itself. Throw a warning.
1343 // But wait; there are exceptions!
1344 // Exception #1: The field may not belong to this record.
1345 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001346 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001347 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1348 // Even though the field matches, it does not belong to this record.
1349 return false;
1350 }
1351 // None of the exceptions triggered; return true to indicate an
1352 // uninitialized field was used.
1353 *L = ME->getMemberLoc();
1354 return true;
1355 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001356 } else if (isa<SizeOfAlignOfExpr>(S)) {
1357 // sizeof/alignof doesn't reference contents, do not warn.
1358 return false;
1359 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1360 // address-of doesn't reference contents (the pointer may be dereferenced
1361 // in the same expression but it would be rare; and weird).
1362 if (UOE->getOpcode() == UO_AddrOf)
1363 return false;
John McCallb4190042009-11-04 23:02:40 +00001364 }
John McCall7502c1d2011-02-13 04:07:26 +00001365 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001366 if (!*it) {
1367 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001368 continue;
1369 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001370 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1371 return true;
John McCallb4190042009-11-04 23:02:40 +00001372 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001373 return false;
John McCallb4190042009-11-04 23:02:40 +00001374}
1375
John McCallf312b1e2010-08-26 23:41:50 +00001376MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001377Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001378 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001379 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001380 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001381 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1382 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1383 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001384 "Member must be a FieldDecl or IndirectFieldDecl");
1385
Douglas Gregor464b2f02010-11-05 22:21:31 +00001386 if (Member->isInvalidDecl())
1387 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001388
John McCallb4190042009-11-04 23:02:40 +00001389 // Diagnose value-uses of fields to initialize themselves, e.g.
1390 // foo(foo)
1391 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001392 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001393 for (unsigned i = 0; i < NumArgs; ++i) {
1394 SourceLocation L;
1395 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1396 // FIXME: Return true in the case when other fields are used before being
1397 // uninitialized. For example, let this field be the i'th field. When
1398 // initializing the i'th field, throw a warning if any of the >= i'th
1399 // fields are used, as they are not yet initialized.
1400 // Right now we are only handling the case where the i'th field uses
1401 // itself in its initializer.
1402 Diag(L, diag::warn_field_is_uninit);
1403 }
1404 }
1405
Eli Friedman59c04372009-07-29 19:44:27 +00001406 bool HasDependentArg = false;
1407 for (unsigned i = 0; i < NumArgs; i++)
1408 HasDependentArg |= Args[i]->isTypeDependent();
1409
Chandler Carruth894aed92010-12-06 09:23:57 +00001410 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001411 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001412 // Can't check initialization for a member of dependent type or when
1413 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001414 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1415 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416
1417 // Erase any temporaries within this evaluation context; we're not
1418 // going to track them in the AST, since we'll be rebuilding the
1419 // ASTs during template instantiation.
1420 ExprTemporaries.erase(
1421 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1422 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001423 } else {
1424 // Initialize the member.
1425 InitializedEntity MemberEntity =
1426 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1427 : InitializedEntity::InitializeMember(IndirectMember, 0);
1428 InitializationKind Kind =
1429 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001430
Chandler Carruth894aed92010-12-06 09:23:57 +00001431 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1432
1433 ExprResult MemberInit =
1434 InitSeq.Perform(*this, MemberEntity, Kind,
1435 MultiExprArg(*this, Args, NumArgs), 0);
1436 if (MemberInit.isInvalid())
1437 return true;
1438
1439 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1440
1441 // C++0x [class.base.init]p7:
1442 // The initialization of each base and member constitutes a
1443 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001444 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001445 if (MemberInit.isInvalid())
1446 return true;
1447
1448 // If we are in a dependent context, template instantiation will
1449 // perform this type-checking again. Just save the arguments that we
1450 // received in a ParenListExpr.
1451 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1452 // of the information that we have about the member
1453 // initializer. However, deconstructing the ASTs is a dicey process,
1454 // and this approach is far more likely to get the corner cases right.
1455 if (CurContext->isDependentContext())
1456 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1457 RParenLoc);
1458 else
1459 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001460 }
1461
Chandler Carruth894aed92010-12-06 09:23:57 +00001462 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001463 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001464 IdLoc, LParenLoc, Init,
1465 RParenLoc);
1466 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001467 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001468 IdLoc, LParenLoc, Init,
1469 RParenLoc);
1470 }
Eli Friedman59c04372009-07-29 19:44:27 +00001471}
1472
John McCallf312b1e2010-08-26 23:41:50 +00001473MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001474Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1475 Expr **Args, unsigned NumArgs,
1476 SourceLocation LParenLoc,
1477 SourceLocation RParenLoc,
1478 CXXRecordDecl *ClassDecl,
1479 SourceLocation EllipsisLoc) {
1480 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1481 if (!LangOpts.CPlusPlus0x)
1482 return Diag(Loc, diag::err_delegation_0x_only)
1483 << TInfo->getTypeLoc().getLocalSourceRange();
1484
1485 return Diag(Loc, diag::err_delegation_unimplemented)
1486 << TInfo->getTypeLoc().getLocalSourceRange();
1487}
1488
1489MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001490Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001491 Expr **Args, unsigned NumArgs,
1492 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001493 CXXRecordDecl *ClassDecl,
1494 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001495 bool HasDependentArg = false;
1496 for (unsigned i = 0; i < NumArgs; i++)
1497 HasDependentArg |= Args[i]->isTypeDependent();
1498
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001499 SourceLocation BaseLoc
1500 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1501
1502 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1503 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1504 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1505
1506 // C++ [class.base.init]p2:
1507 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001508 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001509 // of that class, the mem-initializer is ill-formed. A
1510 // mem-initializer-list can initialize a base class using any
1511 // name that denotes that base class type.
1512 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1513
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001514 if (EllipsisLoc.isValid()) {
1515 // This is a pack expansion.
1516 if (!BaseType->containsUnexpandedParameterPack()) {
1517 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1518 << SourceRange(BaseLoc, RParenLoc);
1519
1520 EllipsisLoc = SourceLocation();
1521 }
1522 } else {
1523 // Check for any unexpanded parameter packs.
1524 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1525 return true;
1526
1527 for (unsigned I = 0; I != NumArgs; ++I)
1528 if (DiagnoseUnexpandedParameterPack(Args[I]))
1529 return true;
1530 }
1531
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001532 // Check for direct and virtual base classes.
1533 const CXXBaseSpecifier *DirectBaseSpec = 0;
1534 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1535 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001536 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1537 BaseType))
1538 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1539 LParenLoc, RParenLoc, ClassDecl,
1540 EllipsisLoc);
1541
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001542 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1543 VirtualBaseSpec);
1544
1545 // C++ [base.class.init]p2:
1546 // Unless the mem-initializer-id names a nonstatic data member of the
1547 // constructor's class or a direct or virtual base of that class, the
1548 // mem-initializer is ill-formed.
1549 if (!DirectBaseSpec && !VirtualBaseSpec) {
1550 // If the class has any dependent bases, then it's possible that
1551 // one of those types will resolve to the same type as
1552 // BaseType. Therefore, just treat this as a dependent base
1553 // class initialization. FIXME: Should we try to check the
1554 // initialization anyway? It seems odd.
1555 if (ClassDecl->hasAnyDependentBases())
1556 Dependent = true;
1557 else
1558 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1559 << BaseType << Context.getTypeDeclType(ClassDecl)
1560 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1561 }
1562 }
1563
1564 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001565 // Can't check initialization for a base of dependent type or when
1566 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001567 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001568 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1569 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001570
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001571 // Erase any temporaries within this evaluation context; we're not
1572 // going to track them in the AST, since we'll be rebuilding the
1573 // ASTs during template instantiation.
1574 ExprTemporaries.erase(
1575 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1576 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Sean Huntcbb67482011-01-08 20:30:50 +00001578 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001579 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001580 LParenLoc,
1581 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001582 RParenLoc,
1583 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001584 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001585
1586 // C++ [base.class.init]p2:
1587 // If a mem-initializer-id is ambiguous because it designates both
1588 // a direct non-virtual base class and an inherited virtual base
1589 // class, the mem-initializer is ill-formed.
1590 if (DirectBaseSpec && VirtualBaseSpec)
1591 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001592 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001593
1594 CXXBaseSpecifier *BaseSpec
1595 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1596 if (!BaseSpec)
1597 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1598
1599 // Initialize the base.
1600 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001601 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001602 InitializationKind Kind =
1603 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1604
1605 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1606
John McCall60d7b3a2010-08-24 06:29:42 +00001607 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001608 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001609 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610 if (BaseInit.isInvalid())
1611 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001612
1613 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001614
1615 // C++0x [class.base.init]p7:
1616 // The initialization of each base and member constitutes a
1617 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001618 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001619 if (BaseInit.isInvalid())
1620 return true;
1621
1622 // If we are in a dependent context, template instantiation will
1623 // perform this type-checking again. Just save the arguments that we
1624 // received in a ParenListExpr.
1625 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1626 // of the information that we have about the base
1627 // initializer. However, deconstructing the ASTs is a dicey process,
1628 // and this approach is far more likely to get the corner cases right.
1629 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001630 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001631 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1632 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001633 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001634 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001635 LParenLoc,
1636 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001637 RParenLoc,
1638 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001639 }
1640
Sean Huntcbb67482011-01-08 20:30:50 +00001641 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001642 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001643 LParenLoc,
1644 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001645 RParenLoc,
1646 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001647}
1648
Anders Carlssone5ef7402010-04-23 03:10:23 +00001649/// ImplicitInitializerKind - How an implicit base or member initializer should
1650/// initialize its base or member.
1651enum ImplicitInitializerKind {
1652 IIK_Default,
1653 IIK_Copy,
1654 IIK_Move
1655};
1656
Anders Carlssondefefd22010-04-23 02:00:02 +00001657static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001658BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001659 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001660 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001661 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001662 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001663 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001664 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1665 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001666
John McCall60d7b3a2010-08-24 06:29:42 +00001667 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001668
1669 switch (ImplicitInitKind) {
1670 case IIK_Default: {
1671 InitializationKind InitKind
1672 = InitializationKind::CreateDefault(Constructor->getLocation());
1673 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1674 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001675 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001676 break;
1677 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001678
Anders Carlssone5ef7402010-04-23 03:10:23 +00001679 case IIK_Copy: {
1680 ParmVarDecl *Param = Constructor->getParamDecl(0);
1681 QualType ParamType = Param->getType().getNonReferenceType();
1682
1683 Expr *CopyCtorArg =
1684 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001685 Constructor->getLocation(), ParamType,
1686 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001687
Anders Carlssonc7957502010-04-24 22:02:54 +00001688 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001689 QualType ArgTy =
1690 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1691 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001692
1693 CXXCastPath BasePath;
1694 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001695 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001696 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001697 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001698
Anders Carlssone5ef7402010-04-23 03:10:23 +00001699 InitializationKind InitKind
1700 = InitializationKind::CreateDirect(Constructor->getLocation(),
1701 SourceLocation(), SourceLocation());
1702 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1703 &CopyCtorArg, 1);
1704 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001705 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001706 break;
1707 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001708
Anders Carlssone5ef7402010-04-23 03:10:23 +00001709 case IIK_Move:
1710 assert(false && "Unhandled initializer kind!");
1711 }
John McCall9ae2f072010-08-23 23:25:46 +00001712
Douglas Gregor53c374f2010-12-07 00:41:46 +00001713 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001714 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001715 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001716
Anders Carlssondefefd22010-04-23 02:00:02 +00001717 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001718 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001719 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1720 SourceLocation()),
1721 BaseSpec->isVirtual(),
1722 SourceLocation(),
1723 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001724 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001725 SourceLocation());
1726
Anders Carlssondefefd22010-04-23 02:00:02 +00001727 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001728}
1729
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001730static bool
1731BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001732 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001733 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001734 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001735 if (Field->isInvalidDecl())
1736 return true;
1737
Chandler Carruthf186b542010-06-29 23:50:44 +00001738 SourceLocation Loc = Constructor->getLocation();
1739
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001740 if (ImplicitInitKind == IIK_Copy) {
1741 ParmVarDecl *Param = Constructor->getParamDecl(0);
1742 QualType ParamType = Param->getType().getNonReferenceType();
1743
1744 Expr *MemberExprBase =
1745 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001746 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001747
1748 // Build a reference to this field within the parameter.
1749 CXXScopeSpec SS;
1750 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1751 Sema::LookupMemberName);
1752 MemberLookup.addDecl(Field, AS_public);
1753 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001754 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001755 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001756 ParamType, Loc,
1757 /*IsArrow=*/false,
1758 SS,
1759 /*FirstQualifierInScope=*/0,
1760 MemberLookup,
1761 /*TemplateArgs=*/0);
1762 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001763 return true;
1764
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001765 // When the field we are copying is an array, create index variables for
1766 // each dimension of the array. We use these index variables to subscript
1767 // the source array, and other clients (e.g., CodeGen) will perform the
1768 // necessary iteration with these index variables.
1769 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1770 QualType BaseType = Field->getType();
1771 QualType SizeType = SemaRef.Context.getSizeType();
1772 while (const ConstantArrayType *Array
1773 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1774 // Create the iteration variable for this array index.
1775 IdentifierInfo *IterationVarName = 0;
1776 {
1777 llvm::SmallString<8> Str;
1778 llvm::raw_svector_ostream OS(Str);
1779 OS << "__i" << IndexVariables.size();
1780 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1781 }
1782 VarDecl *IterationVar
1783 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1784 IterationVarName, SizeType,
1785 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001786 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001787 IndexVariables.push_back(IterationVar);
1788
1789 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001790 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001791 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001792 assert(!IterationVarRef.isInvalid() &&
1793 "Reference to invented variable cannot fail!");
1794
1795 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001796 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001797 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001798 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001799 Loc);
1800 if (CopyCtorArg.isInvalid())
1801 return true;
1802
1803 BaseType = Array->getElementType();
1804 }
1805
1806 // Construct the entity that we will be initializing. For an array, this
1807 // will be first element in the array, which may require several levels
1808 // of array-subscript entities.
1809 llvm::SmallVector<InitializedEntity, 4> Entities;
1810 Entities.reserve(1 + IndexVariables.size());
1811 Entities.push_back(InitializedEntity::InitializeMember(Field));
1812 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1813 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1814 0,
1815 Entities.back()));
1816
1817 // Direct-initialize to use the copy constructor.
1818 InitializationKind InitKind =
1819 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1820
1821 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1822 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1823 &CopyCtorArgE, 1);
1824
John McCall60d7b3a2010-08-24 06:29:42 +00001825 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001826 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001827 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001828 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001829 if (MemberInit.isInvalid())
1830 return true;
1831
1832 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001833 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001834 MemberInit.takeAs<Expr>(), Loc,
1835 IndexVariables.data(),
1836 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001837 return false;
1838 }
1839
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001840 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1841
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001842 QualType FieldBaseElementType =
1843 SemaRef.Context.getBaseElementType(Field->getType());
1844
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001845 if (FieldBaseElementType->isRecordType()) {
1846 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001847 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001848 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001849
1850 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001851 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001852 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001853
Douglas Gregor53c374f2010-12-07 00:41:46 +00001854 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001855 if (MemberInit.isInvalid())
1856 return true;
1857
1858 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001859 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001860 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001861 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001862 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001863 return false;
1864 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001865
1866 if (FieldBaseElementType->isReferenceType()) {
1867 SemaRef.Diag(Constructor->getLocation(),
1868 diag::err_uninitialized_member_in_ctor)
1869 << (int)Constructor->isImplicit()
1870 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1871 << 0 << Field->getDeclName();
1872 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1873 return true;
1874 }
1875
1876 if (FieldBaseElementType.isConstQualified()) {
1877 SemaRef.Diag(Constructor->getLocation(),
1878 diag::err_uninitialized_member_in_ctor)
1879 << (int)Constructor->isImplicit()
1880 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1881 << 1 << Field->getDeclName();
1882 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1883 return true;
1884 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001885
1886 // Nothing to initialize.
1887 CXXMemberInit = 0;
1888 return false;
1889}
John McCallf1860e52010-05-20 23:23:51 +00001890
1891namespace {
1892struct BaseAndFieldInfo {
1893 Sema &S;
1894 CXXConstructorDecl *Ctor;
1895 bool AnyErrorsInInits;
1896 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001897 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1898 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001899
1900 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1901 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1902 // FIXME: Handle implicit move constructors.
1903 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1904 IIK = IIK_Copy;
1905 else
1906 IIK = IIK_Default;
1907 }
1908};
1909}
1910
1911static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1912 FieldDecl *Top, FieldDecl *Field) {
1913
Chandler Carruthe861c602010-06-30 02:59:29 +00001914 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00001915 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001916 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001917 return false;
1918 }
1919
1920 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1921 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1922 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001923 CXXRecordDecl *FieldClassDecl
1924 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001925
1926 // Even though union members never have non-trivial default
1927 // constructions in C++03, we still build member initializers for aggregate
1928 // record types which can be union members, and C++0x allows non-trivial
1929 // default constructors for union members, so we ensure that only one
1930 // member is initialized for these.
1931 if (FieldClassDecl->isUnion()) {
1932 // First check for an explicit initializer for one field.
1933 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1934 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00001935 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001936 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001937
1938 // Once we've initialized a field of an anonymous union, the union
1939 // field in the class is also initialized, so exit immediately.
1940 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001941 } else if ((*FA)->isAnonymousStructOrUnion()) {
1942 if (CollectFieldInitializer(Info, Top, *FA))
1943 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001944 }
1945 }
1946
1947 // Fallthrough and construct a default initializer for the union as
1948 // a whole, which can call its default constructor if such a thing exists
1949 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1950 // behavior going forward with C++0x, when anonymous unions there are
1951 // finalized, we should revisit this.
1952 } else {
1953 // For structs, we simply descend through to initialize all members where
1954 // necessary.
1955 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1956 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1957 if (CollectFieldInitializer(Info, Top, *FA))
1958 return true;
1959 }
1960 }
John McCallf1860e52010-05-20 23:23:51 +00001961 }
1962
1963 // Don't try to build an implicit initializer if there were semantic
1964 // errors in any of the initializers (and therefore we might be
1965 // missing some that the user actually wrote).
1966 if (Info.AnyErrorsInInits)
1967 return false;
1968
Sean Huntcbb67482011-01-08 20:30:50 +00001969 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00001970 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1971 return true;
John McCallf1860e52010-05-20 23:23:51 +00001972
Francois Pichet00eb3f92010-12-04 09:14:42 +00001973 if (Init)
1974 Info.AllToInit.push_back(Init);
1975
John McCallf1860e52010-05-20 23:23:51 +00001976 return false;
1977}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001978
Eli Friedman80c30da2009-11-09 19:20:36 +00001979bool
Sean Huntcbb67482011-01-08 20:30:50 +00001980Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1981 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001982 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001983 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001984 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001985 // Just store the initializers as written, they will be checked during
1986 // instantiation.
1987 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00001988 Constructor->setNumCtorInitializers(NumInitializers);
1989 CXXCtorInitializer **baseOrMemberInitializers =
1990 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001991 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00001992 NumInitializers * sizeof(CXXCtorInitializer*));
1993 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001994 }
1995
1996 return false;
1997 }
1998
John McCallf1860e52010-05-20 23:23:51 +00001999 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002000
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002001 // We need to build the initializer AST according to order of construction
2002 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002003 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002004 if (!ClassDecl)
2005 return true;
2006
Eli Friedman80c30da2009-11-09 19:20:36 +00002007 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002009 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002010 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002011
2012 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002013 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002014 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002015 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002016 }
2017
Anders Carlsson711f34a2010-04-21 19:52:01 +00002018 // Keep track of the direct virtual bases.
2019 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2020 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2021 E = ClassDecl->bases_end(); I != E; ++I) {
2022 if (I->isVirtual())
2023 DirectVBases.insert(I);
2024 }
2025
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002026 // Push virtual bases before others.
2027 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2028 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2029
Sean Huntcbb67482011-01-08 20:30:50 +00002030 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002031 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2032 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002033 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002034 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002035 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002036 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002037 VBase, IsInheritedVirtualBase,
2038 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002039 HadError = true;
2040 continue;
2041 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002042
John McCallf1860e52010-05-20 23:23:51 +00002043 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002044 }
2045 }
Mike Stump1eb44332009-09-09 15:08:12 +00002046
John McCallf1860e52010-05-20 23:23:51 +00002047 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002048 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2049 E = ClassDecl->bases_end(); Base != E; ++Base) {
2050 // Virtuals are in the virtual base list and already constructed.
2051 if (Base->isVirtual())
2052 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Sean Huntcbb67482011-01-08 20:30:50 +00002054 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002055 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2056 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002057 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002058 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002059 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002060 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002061 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002062 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002063 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002064 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002065
John McCallf1860e52010-05-20 23:23:51 +00002066 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002067 }
2068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
John McCallf1860e52010-05-20 23:23:51 +00002070 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002071 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002072 E = ClassDecl->field_end(); Field != E; ++Field) {
2073 if ((*Field)->getType()->isIncompleteArrayType()) {
2074 assert(ClassDecl->hasFlexibleArrayMember() &&
2075 "Incomplete array type is not valid");
2076 continue;
2077 }
John McCallf1860e52010-05-20 23:23:51 +00002078 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002079 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081
John McCallf1860e52010-05-20 23:23:51 +00002082 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002083 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002084 Constructor->setNumCtorInitializers(NumInitializers);
2085 CXXCtorInitializer **baseOrMemberInitializers =
2086 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002087 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002088 NumInitializers * sizeof(CXXCtorInitializer*));
2089 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002090
John McCallef027fe2010-03-16 21:39:52 +00002091 // Constructors implicitly reference the base and member
2092 // destructors.
2093 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2094 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002095 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002096
2097 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002098}
2099
Eli Friedman6347f422009-07-21 19:28:10 +00002100static void *GetKeyForTopLevelField(FieldDecl *Field) {
2101 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002102 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002103 if (RT->getDecl()->isAnonymousStructOrUnion())
2104 return static_cast<void *>(RT->getDecl());
2105 }
2106 return static_cast<void *>(Field);
2107}
2108
Anders Carlssonea356fb2010-04-02 05:42:15 +00002109static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002110 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002111}
2112
Anders Carlssonea356fb2010-04-02 05:42:15 +00002113static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002114 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002115 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002116 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002117
Eli Friedman6347f422009-07-21 19:28:10 +00002118 // For fields injected into the class via declaration of an anonymous union,
2119 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002120 FieldDecl *Field = Member->getAnyMember();
2121
John McCall3c3ccdb2010-04-10 09:28:51 +00002122 // If the field is a member of an anonymous struct or union, our key
2123 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002124 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002125 if (RD->isAnonymousStructOrUnion()) {
2126 while (true) {
2127 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2128 if (Parent->isAnonymousStructOrUnion())
2129 RD = Parent;
2130 else
2131 break;
2132 }
2133
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002134 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002137 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002138}
2139
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002140static void
2141DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002142 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002143 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002144 unsigned NumInits) {
2145 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002146 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002148 // Don't check initializers order unless the warning is enabled at the
2149 // location of at least one initializer.
2150 bool ShouldCheckOrder = false;
2151 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002152 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002153 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2154 Init->getSourceLocation())
2155 != Diagnostic::Ignored) {
2156 ShouldCheckOrder = true;
2157 break;
2158 }
2159 }
2160 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002161 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002162
John McCalld6ca8da2010-04-10 07:37:23 +00002163 // Build the list of bases and members in the order that they'll
2164 // actually be initialized. The explicit initializers should be in
2165 // this same order but may be missing things.
2166 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Anders Carlsson071d6102010-04-02 03:38:04 +00002168 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2169
John McCalld6ca8da2010-04-10 07:37:23 +00002170 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002171 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002172 ClassDecl->vbases_begin(),
2173 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002174 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002175
John McCalld6ca8da2010-04-10 07:37:23 +00002176 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002177 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002178 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002179 if (Base->isVirtual())
2180 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002181 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
John McCalld6ca8da2010-04-10 07:37:23 +00002184 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002185 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2186 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002187 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002188
John McCalld6ca8da2010-04-10 07:37:23 +00002189 unsigned NumIdealInits = IdealInitKeys.size();
2190 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002191
Sean Huntcbb67482011-01-08 20:30:50 +00002192 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002193 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002194 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002195 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002196
2197 // Scan forward to try to find this initializer in the idealized
2198 // initializers list.
2199 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2200 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002201 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002202
2203 // If we didn't find this initializer, it must be because we
2204 // scanned past it on a previous iteration. That can only
2205 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002206 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002207 Sema::SemaDiagnosticBuilder D =
2208 SemaRef.Diag(PrevInit->getSourceLocation(),
2209 diag::warn_initializer_out_of_order);
2210
Francois Pichet00eb3f92010-12-04 09:14:42 +00002211 if (PrevInit->isAnyMemberInitializer())
2212 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002213 else
2214 D << 1 << PrevInit->getBaseClassInfo()->getType();
2215
Francois Pichet00eb3f92010-12-04 09:14:42 +00002216 if (Init->isAnyMemberInitializer())
2217 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002218 else
2219 D << 1 << Init->getBaseClassInfo()->getType();
2220
2221 // Move back to the initializer's location in the ideal list.
2222 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2223 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002224 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002225
2226 assert(IdealIndex != NumIdealInits &&
2227 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002228 }
John McCalld6ca8da2010-04-10 07:37:23 +00002229
2230 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002231 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002232}
2233
John McCall3c3ccdb2010-04-10 09:28:51 +00002234namespace {
2235bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002236 CXXCtorInitializer *Init,
2237 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002238 if (!PrevInit) {
2239 PrevInit = Init;
2240 return false;
2241 }
2242
2243 if (FieldDecl *Field = Init->getMember())
2244 S.Diag(Init->getSourceLocation(),
2245 diag::err_multiple_mem_initialization)
2246 << Field->getDeclName()
2247 << Init->getSourceRange();
2248 else {
John McCallf4c73712011-01-19 06:33:43 +00002249 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002250 assert(BaseClass && "neither field nor base");
2251 S.Diag(Init->getSourceLocation(),
2252 diag::err_multiple_base_initialization)
2253 << QualType(BaseClass, 0)
2254 << Init->getSourceRange();
2255 }
2256 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2257 << 0 << PrevInit->getSourceRange();
2258
2259 return true;
2260}
2261
Sean Huntcbb67482011-01-08 20:30:50 +00002262typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002263typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2264
2265bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002266 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002267 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002268 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002269 RecordDecl *Parent = Field->getParent();
2270 if (!Parent->isAnonymousStructOrUnion())
2271 return false;
2272
2273 NamedDecl *Child = Field;
2274 do {
2275 if (Parent->isUnion()) {
2276 UnionEntry &En = Unions[Parent];
2277 if (En.first && En.first != Child) {
2278 S.Diag(Init->getSourceLocation(),
2279 diag::err_multiple_mem_union_initialization)
2280 << Field->getDeclName()
2281 << Init->getSourceRange();
2282 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2283 << 0 << En.second->getSourceRange();
2284 return true;
2285 } else if (!En.first) {
2286 En.first = Child;
2287 En.second = Init;
2288 }
2289 }
2290
2291 Child = Parent;
2292 Parent = cast<RecordDecl>(Parent->getDeclContext());
2293 } while (Parent->isAnonymousStructOrUnion());
2294
2295 return false;
2296}
2297}
2298
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002299/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002300void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002301 SourceLocation ColonLoc,
2302 MemInitTy **meminits, unsigned NumMemInits,
2303 bool AnyErrors) {
2304 if (!ConstructorDecl)
2305 return;
2306
2307 AdjustDeclIfTemplate(ConstructorDecl);
2308
2309 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002310 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002311
2312 if (!Constructor) {
2313 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2314 return;
2315 }
2316
Sean Huntcbb67482011-01-08 20:30:50 +00002317 CXXCtorInitializer **MemInits =
2318 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002319
2320 // Mapping for the duplicate initializers check.
2321 // For member initializers, this is keyed with a FieldDecl*.
2322 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002323 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002324
2325 // Mapping for the inconsistent anonymous-union initializers check.
2326 RedundantUnionMap MemberUnions;
2327
Anders Carlssonea356fb2010-04-02 05:42:15 +00002328 bool HadError = false;
2329 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002330 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002331
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002332 // Set the source order index.
2333 Init->setSourceOrder(i);
2334
Francois Pichet00eb3f92010-12-04 09:14:42 +00002335 if (Init->isAnyMemberInitializer()) {
2336 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002337 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2338 CheckRedundantUnionInit(*this, Init, MemberUnions))
2339 HadError = true;
2340 } else {
2341 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2342 if (CheckRedundantInit(*this, Init, Members[Key]))
2343 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002344 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002345 }
2346
Anders Carlssonea356fb2010-04-02 05:42:15 +00002347 if (HadError)
2348 return;
2349
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002350 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002351
Sean Huntcbb67482011-01-08 20:30:50 +00002352 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002353}
2354
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002355void
John McCallef027fe2010-03-16 21:39:52 +00002356Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2357 CXXRecordDecl *ClassDecl) {
2358 // Ignore dependent contexts.
2359 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002360 return;
John McCall58e6f342010-03-16 05:22:47 +00002361
2362 // FIXME: all the access-control diagnostics are positioned on the
2363 // field/base declaration. That's probably good; that said, the
2364 // user might reasonably want to know why the destructor is being
2365 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002366
Anders Carlsson9f853df2009-11-17 04:44:12 +00002367 // Non-static data members.
2368 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2369 E = ClassDecl->field_end(); I != E; ++I) {
2370 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002371 if (Field->isInvalidDecl())
2372 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002373 QualType FieldType = Context.getBaseElementType(Field->getType());
2374
2375 const RecordType* RT = FieldType->getAs<RecordType>();
2376 if (!RT)
2377 continue;
2378
2379 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2380 if (FieldClassDecl->hasTrivialDestructor())
2381 continue;
2382
Douglas Gregordb89f282010-07-01 22:47:18 +00002383 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002384 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002385 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002386 << Field->getDeclName()
2387 << FieldType);
2388
John McCallef027fe2010-03-16 21:39:52 +00002389 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002390 }
2391
John McCall58e6f342010-03-16 05:22:47 +00002392 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2393
Anders Carlsson9f853df2009-11-17 04:44:12 +00002394 // Bases.
2395 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2396 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002397 // Bases are always records in a well-formed non-dependent class.
2398 const RecordType *RT = Base->getType()->getAs<RecordType>();
2399
2400 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002401 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002402 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002403
2404 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002405 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002406 if (BaseClassDecl->hasTrivialDestructor())
2407 continue;
John McCall58e6f342010-03-16 05:22:47 +00002408
Douglas Gregordb89f282010-07-01 22:47:18 +00002409 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002410
2411 // FIXME: caret should be on the start of the class name
2412 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002413 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002414 << Base->getType()
2415 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002416
John McCallef027fe2010-03-16 21:39:52 +00002417 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002418 }
2419
2420 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002421 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2422 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002423
2424 // Bases are always records in a well-formed non-dependent class.
2425 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2426
2427 // Ignore direct virtual bases.
2428 if (DirectVirtualBases.count(RT))
2429 continue;
2430
Anders Carlsson9f853df2009-11-17 04:44:12 +00002431 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002432 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002433 if (BaseClassDecl->hasTrivialDestructor())
2434 continue;
John McCall58e6f342010-03-16 05:22:47 +00002435
Douglas Gregordb89f282010-07-01 22:47:18 +00002436 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002437 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002438 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002439 << VBase->getType());
2440
John McCallef027fe2010-03-16 21:39:52 +00002441 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002442 }
2443}
2444
John McCalld226f652010-08-21 09:40:31 +00002445void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002446 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002447 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Mike Stump1eb44332009-09-09 15:08:12 +00002449 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002450 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002451 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002452}
2453
Mike Stump1eb44332009-09-09 15:08:12 +00002454bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002455 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002456 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002457 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002458 else
John McCall94c3b562010-08-18 09:41:07 +00002459 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002460}
2461
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002462bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002463 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002464 if (!getLangOptions().CPlusPlus)
2465 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Anders Carlsson11f21a02009-03-23 19:10:31 +00002467 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002468 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Ted Kremenek6217b802009-07-29 21:53:49 +00002470 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002471 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002472 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002473 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002475 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002476 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002477 }
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Ted Kremenek6217b802009-07-29 21:53:49 +00002479 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002480 if (!RT)
2481 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002482
John McCall86ff3082010-02-04 22:26:26 +00002483 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002484
John McCall94c3b562010-08-18 09:41:07 +00002485 // We can't answer whether something is abstract until it has a
2486 // definition. If it's currently being defined, we'll walk back
2487 // over all the declarations when we have a full definition.
2488 const CXXRecordDecl *Def = RD->getDefinition();
2489 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002490 return false;
2491
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002492 if (!RD->isAbstract())
2493 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002495 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002496 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002497
John McCall94c3b562010-08-18 09:41:07 +00002498 return true;
2499}
2500
2501void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2502 // Check if we've already emitted the list of pure virtual functions
2503 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002504 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002505 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002507 CXXFinalOverriderMap FinalOverriders;
2508 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002510 // Keep a set of seen pure methods so we won't diagnose the same method
2511 // more than once.
2512 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2513
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002514 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2515 MEnd = FinalOverriders.end();
2516 M != MEnd;
2517 ++M) {
2518 for (OverridingMethods::iterator SO = M->second.begin(),
2519 SOEnd = M->second.end();
2520 SO != SOEnd; ++SO) {
2521 // C++ [class.abstract]p4:
2522 // A class is abstract if it contains or inherits at least one
2523 // pure virtual function for which the final overrider is pure
2524 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002525
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002526 //
2527 if (SO->second.size() != 1)
2528 continue;
2529
2530 if (!SO->second.front().Method->isPure())
2531 continue;
2532
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002533 if (!SeenPureMethods.insert(SO->second.front().Method))
2534 continue;
2535
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002536 Diag(SO->second.front().Method->getLocation(),
2537 diag::note_pure_virtual_function)
2538 << SO->second.front().Method->getDeclName();
2539 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002540 }
2541
2542 if (!PureVirtualClassDiagSet)
2543 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2544 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002545}
2546
Anders Carlsson8211eff2009-03-24 01:19:16 +00002547namespace {
John McCall94c3b562010-08-18 09:41:07 +00002548struct AbstractUsageInfo {
2549 Sema &S;
2550 CXXRecordDecl *Record;
2551 CanQualType AbstractType;
2552 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002553
John McCall94c3b562010-08-18 09:41:07 +00002554 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2555 : S(S), Record(Record),
2556 AbstractType(S.Context.getCanonicalType(
2557 S.Context.getTypeDeclType(Record))),
2558 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002559
John McCall94c3b562010-08-18 09:41:07 +00002560 void DiagnoseAbstractType() {
2561 if (Invalid) return;
2562 S.DiagnoseAbstractType(Record);
2563 Invalid = true;
2564 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002565
John McCall94c3b562010-08-18 09:41:07 +00002566 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2567};
2568
2569struct CheckAbstractUsage {
2570 AbstractUsageInfo &Info;
2571 const NamedDecl *Ctx;
2572
2573 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2574 : Info(Info), Ctx(Ctx) {}
2575
2576 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2577 switch (TL.getTypeLocClass()) {
2578#define ABSTRACT_TYPELOC(CLASS, PARENT)
2579#define TYPELOC(CLASS, PARENT) \
2580 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2581#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002582 }
John McCall94c3b562010-08-18 09:41:07 +00002583 }
Mike Stump1eb44332009-09-09 15:08:12 +00002584
John McCall94c3b562010-08-18 09:41:07 +00002585 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2586 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2587 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2588 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2589 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002590 }
John McCall94c3b562010-08-18 09:41:07 +00002591 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002592
John McCall94c3b562010-08-18 09:41:07 +00002593 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2594 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2595 }
Mike Stump1eb44332009-09-09 15:08:12 +00002596
John McCall94c3b562010-08-18 09:41:07 +00002597 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2598 // Visit the type parameters from a permissive context.
2599 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2600 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2601 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2602 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2603 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2604 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002605 }
John McCall94c3b562010-08-18 09:41:07 +00002606 }
Mike Stump1eb44332009-09-09 15:08:12 +00002607
John McCall94c3b562010-08-18 09:41:07 +00002608 // Visit pointee types from a permissive context.
2609#define CheckPolymorphic(Type) \
2610 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2611 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2612 }
2613 CheckPolymorphic(PointerTypeLoc)
2614 CheckPolymorphic(ReferenceTypeLoc)
2615 CheckPolymorphic(MemberPointerTypeLoc)
2616 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002617
John McCall94c3b562010-08-18 09:41:07 +00002618 /// Handle all the types we haven't given a more specific
2619 /// implementation for above.
2620 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2621 // Every other kind of type that we haven't called out already
2622 // that has an inner type is either (1) sugar or (2) contains that
2623 // inner type in some way as a subobject.
2624 if (TypeLoc Next = TL.getNextTypeLoc())
2625 return Visit(Next, Sel);
2626
2627 // If there's no inner type and we're in a permissive context,
2628 // don't diagnose.
2629 if (Sel == Sema::AbstractNone) return;
2630
2631 // Check whether the type matches the abstract type.
2632 QualType T = TL.getType();
2633 if (T->isArrayType()) {
2634 Sel = Sema::AbstractArrayType;
2635 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002636 }
John McCall94c3b562010-08-18 09:41:07 +00002637 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2638 if (CT != Info.AbstractType) return;
2639
2640 // It matched; do some magic.
2641 if (Sel == Sema::AbstractArrayType) {
2642 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2643 << T << TL.getSourceRange();
2644 } else {
2645 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2646 << Sel << T << TL.getSourceRange();
2647 }
2648 Info.DiagnoseAbstractType();
2649 }
2650};
2651
2652void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2653 Sema::AbstractDiagSelID Sel) {
2654 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2655}
2656
2657}
2658
2659/// Check for invalid uses of an abstract type in a method declaration.
2660static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2661 CXXMethodDecl *MD) {
2662 // No need to do the check on definitions, which require that
2663 // the return/param types be complete.
2664 if (MD->isThisDeclarationADefinition())
2665 return;
2666
2667 // For safety's sake, just ignore it if we don't have type source
2668 // information. This should never happen for non-implicit methods,
2669 // but...
2670 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2671 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2672}
2673
2674/// Check for invalid uses of an abstract type within a class definition.
2675static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2676 CXXRecordDecl *RD) {
2677 for (CXXRecordDecl::decl_iterator
2678 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2679 Decl *D = *I;
2680 if (D->isImplicit()) continue;
2681
2682 // Methods and method templates.
2683 if (isa<CXXMethodDecl>(D)) {
2684 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2685 } else if (isa<FunctionTemplateDecl>(D)) {
2686 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2687 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2688
2689 // Fields and static variables.
2690 } else if (isa<FieldDecl>(D)) {
2691 FieldDecl *FD = cast<FieldDecl>(D);
2692 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2693 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2694 } else if (isa<VarDecl>(D)) {
2695 VarDecl *VD = cast<VarDecl>(D);
2696 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2697 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2698
2699 // Nested classes and class templates.
2700 } else if (isa<CXXRecordDecl>(D)) {
2701 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2702 } else if (isa<ClassTemplateDecl>(D)) {
2703 CheckAbstractClassUsage(Info,
2704 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2705 }
2706 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002707}
2708
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002709/// \brief Perform semantic checks on a class definition that has been
2710/// completing, introducing implicitly-declared members, checking for
2711/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002712void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002713 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002714 return;
2715
John McCall94c3b562010-08-18 09:41:07 +00002716 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2717 AbstractUsageInfo Info(*this, Record);
2718 CheckAbstractClassUsage(Info, Record);
2719 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002720
2721 // If this is not an aggregate type and has no user-declared constructor,
2722 // complain about any non-static data members of reference or const scalar
2723 // type, since they will never get initializers.
2724 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2725 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2726 bool Complained = false;
2727 for (RecordDecl::field_iterator F = Record->field_begin(),
2728 FEnd = Record->field_end();
2729 F != FEnd; ++F) {
2730 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002731 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002732 if (!Complained) {
2733 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2734 << Record->getTagKind() << Record;
2735 Complained = true;
2736 }
2737
2738 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2739 << F->getType()->isReferenceType()
2740 << F->getDeclName();
2741 }
2742 }
2743 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002744
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002745 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002746 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002747
2748 if (Record->getIdentifier()) {
2749 // C++ [class.mem]p13:
2750 // If T is the name of a class, then each of the following shall have a
2751 // name different from T:
2752 // - every member of every anonymous union that is a member of class T.
2753 //
2754 // C++ [class.mem]p14:
2755 // In addition, if class T has a user-declared constructor (12.1), every
2756 // non-static data member of class T shall have a name different from T.
2757 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002758 R.first != R.second; ++R.first) {
2759 NamedDecl *D = *R.first;
2760 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2761 isa<IndirectFieldDecl>(D)) {
2762 Diag(D->getLocation(), diag::err_member_name_of_class)
2763 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002764 break;
2765 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002766 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002767 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002768
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002769 // Warn if the class has virtual methods but non-virtual public destructor.
Argyrios Kyrtzidis668fdd82011-02-02 18:47:41 +00002770 if (Record->isDynamicClass() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002771 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002772 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002773 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2774 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2775 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002776
2777 // See if a method overloads virtual methods in a base
2778 /// class without overriding any.
2779 if (!Record->isDependentType()) {
2780 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2781 MEnd = Record->method_end();
2782 M != MEnd; ++M) {
2783 DiagnoseHiddenVirtualMethods(Record, *M);
2784 }
2785 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002786
2787 // Declare inherited constructors. We do this eagerly here because:
2788 // - The standard requires an eager diagnostic for conflicting inherited
2789 // constructors from different classes.
2790 // - The lazy declaration of the other implicit constructors is so as to not
2791 // waste space and performance on classes that are not meant to be
2792 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2793 // have inherited constructors.
2794 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002795}
2796
2797/// \brief Data used with FindHiddenVirtualMethod
2798struct FindHiddenVirtualMethodData {
2799 Sema *S;
2800 CXXMethodDecl *Method;
2801 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2802 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2803};
2804
2805/// \brief Member lookup function that determines whether a given C++
2806/// method overloads virtual methods in a base class without overriding any,
2807/// to be used with CXXRecordDecl::lookupInBases().
2808static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2809 CXXBasePath &Path,
2810 void *UserData) {
2811 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2812
2813 FindHiddenVirtualMethodData &Data
2814 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2815
2816 DeclarationName Name = Data.Method->getDeclName();
2817 assert(Name.getNameKind() == DeclarationName::Identifier);
2818
2819 bool foundSameNameMethod = false;
2820 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2821 for (Path.Decls = BaseRecord->lookup(Name);
2822 Path.Decls.first != Path.Decls.second;
2823 ++Path.Decls.first) {
2824 NamedDecl *D = *Path.Decls.first;
2825 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002826 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002827 foundSameNameMethod = true;
2828 // Interested only in hidden virtual methods.
2829 if (!MD->isVirtual())
2830 continue;
2831 // If the method we are checking overrides a method from its base
2832 // don't warn about the other overloaded methods.
2833 if (!Data.S->IsOverload(Data.Method, MD, false))
2834 return true;
2835 // Collect the overload only if its hidden.
2836 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2837 overloadedMethods.push_back(MD);
2838 }
2839 }
2840
2841 if (foundSameNameMethod)
2842 Data.OverloadedMethods.append(overloadedMethods.begin(),
2843 overloadedMethods.end());
2844 return foundSameNameMethod;
2845}
2846
2847/// \brief See if a method overloads virtual methods in a base class without
2848/// overriding any.
2849void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2850 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2851 MD->getLocation()) == Diagnostic::Ignored)
2852 return;
2853 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2854 return;
2855
2856 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2857 /*bool RecordPaths=*/false,
2858 /*bool DetectVirtual=*/false);
2859 FindHiddenVirtualMethodData Data;
2860 Data.Method = MD;
2861 Data.S = this;
2862
2863 // Keep the base methods that were overriden or introduced in the subclass
2864 // by 'using' in a set. A base method not in this set is hidden.
2865 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2866 res.first != res.second; ++res.first) {
2867 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2868 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2869 E = MD->end_overridden_methods();
2870 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002871 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002872 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2873 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002874 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002875 }
2876
2877 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2878 !Data.OverloadedMethods.empty()) {
2879 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2880 << MD << (Data.OverloadedMethods.size() > 1);
2881
2882 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2883 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2884 Diag(overloadedMD->getLocation(),
2885 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2886 }
2887 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002888}
2889
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002890void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002891 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002892 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002893 SourceLocation RBrac,
2894 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002895 if (!TagDecl)
2896 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Douglas Gregor42af25f2009-05-11 19:58:34 +00002898 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002899
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002900 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002901 // strict aliasing violation!
2902 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002903 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002904
Douglas Gregor23c94db2010-07-02 17:43:08 +00002905 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002906 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002907}
2908
Douglas Gregord92ec472010-07-01 05:10:53 +00002909namespace {
2910 /// \brief Helper class that collects exception specifications for
2911 /// implicitly-declared special member functions.
2912 class ImplicitExceptionSpecification {
2913 ASTContext &Context;
2914 bool AllowsAllExceptions;
2915 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2916 llvm::SmallVector<QualType, 4> Exceptions;
2917
2918 public:
2919 explicit ImplicitExceptionSpecification(ASTContext &Context)
2920 : Context(Context), AllowsAllExceptions(false) { }
2921
2922 /// \brief Whether the special member function should have any
2923 /// exception specification at all.
2924 bool hasExceptionSpecification() const {
2925 return !AllowsAllExceptions;
2926 }
2927
2928 /// \brief Whether the special member function should have a
2929 /// throw(...) exception specification (a Microsoft extension).
2930 bool hasAnyExceptionSpecification() const {
2931 return false;
2932 }
2933
2934 /// \brief The number of exceptions in the exception specification.
2935 unsigned size() const { return Exceptions.size(); }
2936
2937 /// \brief The set of exceptions in the exception specification.
2938 const QualType *data() const { return Exceptions.data(); }
2939
2940 /// \brief Note that
2941 void CalledDecl(CXXMethodDecl *Method) {
2942 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002943 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002944 return;
2945
2946 const FunctionProtoType *Proto
2947 = Method->getType()->getAs<FunctionProtoType>();
2948
2949 // If this function can throw any exceptions, make a note of that.
2950 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2951 AllowsAllExceptions = true;
2952 ExceptionsSeen.clear();
2953 Exceptions.clear();
2954 return;
2955 }
2956
2957 // Record the exceptions in this function's exception specification.
2958 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2959 EEnd = Proto->exception_end();
2960 E != EEnd; ++E)
2961 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2962 Exceptions.push_back(*E);
2963 }
2964 };
2965}
2966
2967
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002968/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2969/// special functions, such as the default constructor, copy
2970/// constructor, or destructor, to the given C++ class (C++
2971/// [special]p1). This routine can only be executed just before the
2972/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002973void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002974 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002975 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002976
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002977 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002978 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002979
Douglas Gregora376d102010-07-02 21:50:04 +00002980 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2981 ++ASTContext::NumImplicitCopyAssignmentOperators;
2982
2983 // If we have a dynamic class, then the copy assignment operator may be
2984 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2985 // it shows up in the right place in the vtable and that we diagnose
2986 // problems with the implicit exception specification.
2987 if (ClassDecl->isDynamicClass())
2988 DeclareImplicitCopyAssignment(ClassDecl);
2989 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002990
Douglas Gregor4923aa22010-07-02 20:37:36 +00002991 if (!ClassDecl->hasUserDeclaredDestructor()) {
2992 ++ASTContext::NumImplicitDestructors;
2993
2994 // If we have a dynamic class, then the destructor may be virtual, so we
2995 // have to declare the destructor immediately. This ensures that, e.g., it
2996 // shows up in the right place in the vtable and that we diagnose problems
2997 // with the implicit exception specification.
2998 if (ClassDecl->isDynamicClass())
2999 DeclareImplicitDestructor(ClassDecl);
3000 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003001}
3002
John McCalld226f652010-08-21 09:40:31 +00003003void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003004 if (!D)
3005 return;
3006
3007 TemplateParameterList *Params = 0;
3008 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3009 Params = Template->getTemplateParameters();
3010 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3011 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3012 Params = PartialSpec->getTemplateParameters();
3013 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003014 return;
3015
Douglas Gregor6569d682009-05-27 23:11:45 +00003016 for (TemplateParameterList::iterator Param = Params->begin(),
3017 ParamEnd = Params->end();
3018 Param != ParamEnd; ++Param) {
3019 NamedDecl *Named = cast<NamedDecl>(*Param);
3020 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003021 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003022 IdResolver.AddDecl(Named);
3023 }
3024 }
3025}
3026
John McCalld226f652010-08-21 09:40:31 +00003027void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003028 if (!RecordD) return;
3029 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003030 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003031 PushDeclContext(S, Record);
3032}
3033
John McCalld226f652010-08-21 09:40:31 +00003034void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003035 if (!RecordD) return;
3036 PopDeclContext();
3037}
3038
Douglas Gregor72b505b2008-12-16 21:30:33 +00003039/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3040/// parsing a top-level (non-nested) C++ class, and we are now
3041/// parsing those parts of the given Method declaration that could
3042/// not be parsed earlier (C++ [class.mem]p2), such as default
3043/// arguments. This action should enter the scope of the given
3044/// Method declaration as if we had just parsed the qualified method
3045/// name. However, it should not bring the parameters into scope;
3046/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003047void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003048}
3049
3050/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3051/// C++ method declaration. We're (re-)introducing the given
3052/// function parameter into scope for use in parsing later parts of
3053/// the method declaration. For example, we could see an
3054/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003055void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003056 if (!ParamD)
3057 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003058
John McCalld226f652010-08-21 09:40:31 +00003059 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003060
3061 // If this parameter has an unparsed default argument, clear it out
3062 // to make way for the parsed default argument.
3063 if (Param->hasUnparsedDefaultArg())
3064 Param->setDefaultArg(0);
3065
John McCalld226f652010-08-21 09:40:31 +00003066 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003067 if (Param->getDeclName())
3068 IdResolver.AddDecl(Param);
3069}
3070
3071/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3072/// processing the delayed method declaration for Method. The method
3073/// declaration is now considered finished. There may be a separate
3074/// ActOnStartOfFunctionDef action later (not necessarily
3075/// immediately!) for this method, if it was also defined inside the
3076/// class body.
John McCalld226f652010-08-21 09:40:31 +00003077void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003078 if (!MethodD)
3079 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003081 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003082
John McCalld226f652010-08-21 09:40:31 +00003083 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003084
3085 // Now that we have our default arguments, check the constructor
3086 // again. It could produce additional diagnostics or affect whether
3087 // the class has implicitly-declared destructors, among other
3088 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003089 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3090 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003091
3092 // Check the default arguments, which we may have added.
3093 if (!Method->isInvalidDecl())
3094 CheckCXXDefaultArguments(Method);
3095}
3096
Douglas Gregor42a552f2008-11-05 20:51:48 +00003097/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003098/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003099/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003100/// emit diagnostics and set the invalid bit to true. In any case, the type
3101/// will be updated to reflect a well-formed type for the constructor and
3102/// returned.
3103QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003104 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003105 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003106
3107 // C++ [class.ctor]p3:
3108 // A constructor shall not be virtual (10.3) or static (9.4). A
3109 // constructor can be invoked for a const, volatile or const
3110 // volatile object. A constructor shall not be declared const,
3111 // volatile, or const volatile (9.3.2).
3112 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003113 if (!D.isInvalidType())
3114 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3115 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3116 << SourceRange(D.getIdentifierLoc());
3117 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003118 }
John McCalld931b082010-08-26 03:08:43 +00003119 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003120 if (!D.isInvalidType())
3121 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3122 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3123 << SourceRange(D.getIdentifierLoc());
3124 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003125 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003126 }
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003128 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003129 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003130 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3132 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003133 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003134 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3135 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003136 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003137 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3138 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003139 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003140 }
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Douglas Gregorc938c162011-01-26 05:01:58 +00003142 // C++0x [class.ctor]p4:
3143 // A constructor shall not be declared with a ref-qualifier.
3144 if (FTI.hasRefQualifier()) {
3145 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3146 << FTI.RefQualifierIsLValueRef
3147 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3148 D.setInvalidType();
3149 }
3150
Douglas Gregor42a552f2008-11-05 20:51:48 +00003151 // Rebuild the function type "R" without any type qualifiers (in
3152 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003153 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003154 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003155 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3156 return R;
3157
3158 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3159 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003160 EPI.RefQualifier = RQ_None;
3161
Chris Lattner65401802009-04-25 08:28:21 +00003162 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003163 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003164}
3165
Douglas Gregor72b505b2008-12-16 21:30:33 +00003166/// CheckConstructor - Checks a fully-formed constructor for
3167/// well-formedness, issuing any diagnostics required. Returns true if
3168/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003169void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003170 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003171 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3172 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003173 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003174
3175 // C++ [class.copy]p3:
3176 // A declaration of a constructor for a class X is ill-formed if
3177 // its first parameter is of type (optionally cv-qualified) X and
3178 // either there are no other parameters or else all other
3179 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003180 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003181 ((Constructor->getNumParams() == 1) ||
3182 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003183 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3184 Constructor->getTemplateSpecializationKind()
3185 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003186 QualType ParamType = Constructor->getParamDecl(0)->getType();
3187 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3188 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003189 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003190 const char *ConstRef
3191 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3192 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003193 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003194 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003195
3196 // FIXME: Rather that making the constructor invalid, we should endeavor
3197 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003198 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003199 }
3200 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003201}
3202
John McCall15442822010-08-04 01:04:25 +00003203/// CheckDestructor - Checks a fully-formed destructor definition for
3204/// well-formedness, issuing any diagnostics required. Returns true
3205/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003206bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003207 CXXRecordDecl *RD = Destructor->getParent();
3208
3209 if (Destructor->isVirtual()) {
3210 SourceLocation Loc;
3211
3212 if (!Destructor->isImplicit())
3213 Loc = Destructor->getLocation();
3214 else
3215 Loc = RD->getLocation();
3216
3217 // If we have a virtual destructor, look up the deallocation function
3218 FunctionDecl *OperatorDelete = 0;
3219 DeclarationName Name =
3220 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003221 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003222 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003223
3224 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003225
3226 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003227 }
Anders Carlsson37909802009-11-30 21:24:50 +00003228
3229 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003230}
3231
Mike Stump1eb44332009-09-09 15:08:12 +00003232static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003233FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3234 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3235 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003236 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003237}
3238
Douglas Gregor42a552f2008-11-05 20:51:48 +00003239/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3240/// the well-formednes of the destructor declarator @p D with type @p
3241/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003242/// emit diagnostics and set the declarator to invalid. Even if this happens,
3243/// will be updated to reflect a well-formed type for the destructor and
3244/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003245QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003246 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003247 // C++ [class.dtor]p1:
3248 // [...] A typedef-name that names a class is a class-name
3249 // (7.1.3); however, a typedef-name that names a class shall not
3250 // be used as the identifier in the declarator for a destructor
3251 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003252 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003253 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003254 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003255 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003256
3257 // C++ [class.dtor]p2:
3258 // A destructor is used to destroy objects of its class type. A
3259 // destructor takes no parameters, and no return type can be
3260 // specified for it (not even void). The address of a destructor
3261 // shall not be taken. A destructor shall not be static. A
3262 // destructor can be invoked for a const, volatile or const
3263 // volatile object. A destructor shall not be declared const,
3264 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003265 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003266 if (!D.isInvalidType())
3267 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3268 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003269 << SourceRange(D.getIdentifierLoc())
3270 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3271
John McCalld931b082010-08-26 03:08:43 +00003272 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003273 }
Chris Lattner65401802009-04-25 08:28:21 +00003274 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003275 // Destructors don't have return types, but the parser will
3276 // happily parse something like:
3277 //
3278 // class X {
3279 // float ~X();
3280 // };
3281 //
3282 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003283 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3284 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3285 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003286 }
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003288 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003289 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003290 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003291 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3292 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003293 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003294 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3295 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003296 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003297 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3298 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003299 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003300 }
3301
Douglas Gregorc938c162011-01-26 05:01:58 +00003302 // C++0x [class.dtor]p2:
3303 // A destructor shall not be declared with a ref-qualifier.
3304 if (FTI.hasRefQualifier()) {
3305 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3306 << FTI.RefQualifierIsLValueRef
3307 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3308 D.setInvalidType();
3309 }
3310
Douglas Gregor42a552f2008-11-05 20:51:48 +00003311 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003312 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003313 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3314
3315 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003316 FTI.freeArgs();
3317 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003318 }
3319
Mike Stump1eb44332009-09-09 15:08:12 +00003320 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003321 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003322 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003323 D.setInvalidType();
3324 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003325
3326 // Rebuild the function type "R" without any type qualifiers or
3327 // parameters (in case any of the errors above fired) and with
3328 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003329 // types.
John McCalle23cf432010-12-14 08:05:40 +00003330 if (!D.isInvalidType())
3331 return R;
3332
Douglas Gregord92ec472010-07-01 05:10:53 +00003333 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003334 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3335 EPI.Variadic = false;
3336 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003337 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003338 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003339}
3340
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003341/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3342/// well-formednes of the conversion function declarator @p D with
3343/// type @p R. If there are any errors in the declarator, this routine
3344/// will emit diagnostics and return true. Otherwise, it will return
3345/// false. Either way, the type @p R will be updated to reflect a
3346/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003347void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003348 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003349 // C++ [class.conv.fct]p1:
3350 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003351 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003352 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003353 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003354 if (!D.isInvalidType())
3355 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3356 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3357 << SourceRange(D.getIdentifierLoc());
3358 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003359 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003360 }
John McCalla3f81372010-04-13 00:04:31 +00003361
3362 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3363
Chris Lattner6e475012009-04-25 08:35:12 +00003364 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003365 // Conversion functions don't have return types, but the parser will
3366 // happily parse something like:
3367 //
3368 // class X {
3369 // float operator bool();
3370 // };
3371 //
3372 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003373 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3374 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3375 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003376 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003377 }
3378
John McCalla3f81372010-04-13 00:04:31 +00003379 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3380
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003381 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003382 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003383 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3384
3385 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003386 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003387 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003388 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003389 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003390 D.setInvalidType();
3391 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003392
John McCalla3f81372010-04-13 00:04:31 +00003393 // Diagnose "&operator bool()" and other such nonsense. This
3394 // is actually a gcc extension which we don't support.
3395 if (Proto->getResultType() != ConvType) {
3396 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3397 << Proto->getResultType();
3398 D.setInvalidType();
3399 ConvType = Proto->getResultType();
3400 }
3401
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003402 // C++ [class.conv.fct]p4:
3403 // The conversion-type-id shall not represent a function type nor
3404 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003405 if (ConvType->isArrayType()) {
3406 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3407 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003408 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003409 } else if (ConvType->isFunctionType()) {
3410 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3411 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003412 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003413 }
3414
3415 // Rebuild the function type "R" without any parameters (in case any
3416 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003417 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003418 if (D.isInvalidType())
3419 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003420
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003421 // C++0x explicit conversion operators.
3422 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003423 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003424 diag::warn_explicit_conversion_functions)
3425 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003426}
3427
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003428/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3429/// the declaration of the given C++ conversion function. This routine
3430/// is responsible for recording the conversion function in the C++
3431/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003432Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003433 assert(Conversion && "Expected to receive a conversion function declaration");
3434
Douglas Gregor9d350972008-12-12 08:25:50 +00003435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003436
3437 // Make sure we aren't redeclaring the conversion function.
3438 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003439
3440 // C++ [class.conv.fct]p1:
3441 // [...] A conversion function is never used to convert a
3442 // (possibly cv-qualified) object to the (possibly cv-qualified)
3443 // same object type (or a reference to it), to a (possibly
3444 // cv-qualified) base class of that type (or a reference to it),
3445 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003446 // FIXME: Suppress this warning if the conversion function ends up being a
3447 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003448 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003449 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003450 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003451 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003452 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3453 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003454 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003455 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003456 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3457 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003458 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003459 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003460 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003461 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003462 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003463 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003464 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003465 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003466 }
3467
Douglas Gregore80622f2010-09-29 04:25:11 +00003468 if (FunctionTemplateDecl *ConversionTemplate
3469 = Conversion->getDescribedFunctionTemplate())
3470 return ConversionTemplate;
3471
John McCalld226f652010-08-21 09:40:31 +00003472 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003473}
3474
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003475//===----------------------------------------------------------------------===//
3476// Namespace Handling
3477//===----------------------------------------------------------------------===//
3478
John McCallea318642010-08-26 09:15:37 +00003479
3480
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003481/// ActOnStartNamespaceDef - This is called at the start of a namespace
3482/// definition.
John McCalld226f652010-08-21 09:40:31 +00003483Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003484 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003485 SourceLocation IdentLoc,
3486 IdentifierInfo *II,
3487 SourceLocation LBrace,
3488 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003489 // anonymous namespace starts at its left brace
3490 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3491 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003492 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003493 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003494
3495 Scope *DeclRegionScope = NamespcScope->getParent();
3496
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003497 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3498
John McCall90f14502010-12-10 02:59:44 +00003499 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3500 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003501
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003502 if (II) {
3503 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003504 // The identifier in an original-namespace-definition shall not
3505 // have been previously defined in the declarative region in
3506 // which the original-namespace-definition appears. The
3507 // identifier in an original-namespace-definition is the name of
3508 // the namespace. Subsequently in that declarative region, it is
3509 // treated as an original-namespace-name.
3510 //
3511 // Since namespace names are unique in their scope, and we don't
3512 // look through using directives, just
3513 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3514 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Douglas Gregor44b43212008-12-11 16:49:14 +00003516 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3517 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003518 if (Namespc->isInline() != OrigNS->isInline()) {
3519 // inline-ness must match
3520 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3521 << Namespc->isInline();
3522 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3523 Namespc->setInvalidDecl();
3524 // Recover by ignoring the new namespace's inline status.
3525 Namespc->setInline(OrigNS->isInline());
3526 }
3527
Douglas Gregor44b43212008-12-11 16:49:14 +00003528 // Attach this namespace decl to the chain of extended namespace
3529 // definitions.
3530 OrigNS->setNextNamespace(Namespc);
3531 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003532
Mike Stump1eb44332009-09-09 15:08:12 +00003533 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003534 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003535 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003536 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003537 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003538 } else if (PrevDecl) {
3539 // This is an invalid name redefinition.
3540 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3541 << Namespc->getDeclName();
3542 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3543 Namespc->setInvalidDecl();
3544 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003545 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003546 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003547 // This is the first "real" definition of the namespace "std", so update
3548 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003549 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003550 // We had already defined a dummy namespace "std". Link this new
3551 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003552 StdNS->setNextNamespace(Namespc);
3553 StdNS->setLocation(IdentLoc);
3554 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003555 }
3556
3557 // Make our StdNamespace cache point at the first real definition of the
3558 // "std" namespace.
3559 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003560 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003561
3562 PushOnScopeChains(Namespc, DeclRegionScope);
3563 } else {
John McCall9aeed322009-10-01 00:25:31 +00003564 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003565 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003566
3567 // Link the anonymous namespace into its parent.
3568 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003569 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003570 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3571 PrevDecl = TU->getAnonymousNamespace();
3572 TU->setAnonymousNamespace(Namespc);
3573 } else {
3574 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3575 PrevDecl = ND->getAnonymousNamespace();
3576 ND->setAnonymousNamespace(Namespc);
3577 }
3578
3579 // Link the anonymous namespace with its previous declaration.
3580 if (PrevDecl) {
3581 assert(PrevDecl->isAnonymousNamespace());
3582 assert(!PrevDecl->getNextNamespace());
3583 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3584 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003585
3586 if (Namespc->isInline() != PrevDecl->isInline()) {
3587 // inline-ness must match
3588 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3589 << Namespc->isInline();
3590 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3591 Namespc->setInvalidDecl();
3592 // Recover by ignoring the new namespace's inline status.
3593 Namespc->setInline(PrevDecl->isInline());
3594 }
John McCall5fdd7642009-12-16 02:06:49 +00003595 }
John McCall9aeed322009-10-01 00:25:31 +00003596
Douglas Gregora4181472010-03-24 00:46:35 +00003597 CurContext->addDecl(Namespc);
3598
John McCall9aeed322009-10-01 00:25:31 +00003599 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3600 // behaves as if it were replaced by
3601 // namespace unique { /* empty body */ }
3602 // using namespace unique;
3603 // namespace unique { namespace-body }
3604 // where all occurrences of 'unique' in a translation unit are
3605 // replaced by the same identifier and this identifier differs
3606 // from all other identifiers in the entire program.
3607
3608 // We just create the namespace with an empty name and then add an
3609 // implicit using declaration, just like the standard suggests.
3610 //
3611 // CodeGen enforces the "universally unique" aspect by giving all
3612 // declarations semantically contained within an anonymous
3613 // namespace internal linkage.
3614
John McCall5fdd7642009-12-16 02:06:49 +00003615 if (!PrevDecl) {
3616 UsingDirectiveDecl* UD
3617 = UsingDirectiveDecl::Create(Context, CurContext,
3618 /* 'using' */ LBrace,
3619 /* 'namespace' */ SourceLocation(),
3620 /* qualifier */ SourceRange(),
3621 /* NNS */ NULL,
3622 /* identifier */ SourceLocation(),
3623 Namespc,
3624 /* Ancestor */ CurContext);
3625 UD->setImplicit();
3626 CurContext->addDecl(UD);
3627 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003628 }
3629
3630 // Although we could have an invalid decl (i.e. the namespace name is a
3631 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003632 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3633 // for the namespace has the declarations that showed up in that particular
3634 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003635 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003636 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003637}
3638
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003639/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3640/// is a namespace alias, returns the namespace it points to.
3641static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3642 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3643 return AD->getNamespace();
3644 return dyn_cast_or_null<NamespaceDecl>(D);
3645}
3646
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003647/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3648/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003649void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003650 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3651 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3652 Namespc->setRBracLoc(RBrace);
3653 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003654 if (Namespc->hasAttr<VisibilityAttr>())
3655 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003656}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003657
John McCall384aff82010-08-25 07:42:41 +00003658CXXRecordDecl *Sema::getStdBadAlloc() const {
3659 return cast_or_null<CXXRecordDecl>(
3660 StdBadAlloc.get(Context.getExternalSource()));
3661}
3662
3663NamespaceDecl *Sema::getStdNamespace() const {
3664 return cast_or_null<NamespaceDecl>(
3665 StdNamespace.get(Context.getExternalSource()));
3666}
3667
Douglas Gregor66992202010-06-29 17:53:46 +00003668/// \brief Retrieve the special "std" namespace, which may require us to
3669/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003670NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003671 if (!StdNamespace) {
3672 // The "std" namespace has not yet been defined, so build one implicitly.
3673 StdNamespace = NamespaceDecl::Create(Context,
3674 Context.getTranslationUnitDecl(),
3675 SourceLocation(),
3676 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003677 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003678 }
3679
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003680 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003681}
3682
John McCalld226f652010-08-21 09:40:31 +00003683Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003684 SourceLocation UsingLoc,
3685 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003686 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003687 SourceLocation IdentLoc,
3688 IdentifierInfo *NamespcName,
3689 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003690 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3691 assert(NamespcName && "Invalid NamespcName.");
3692 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003693
3694 // This can only happen along a recovery path.
3695 while (S->getFlags() & Scope::TemplateParamScope)
3696 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003697 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003698
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003699 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003700 NestedNameSpecifier *Qualifier = 0;
3701 if (SS.isSet())
3702 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3703
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003704 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003705 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3706 LookupParsedName(R, S, &SS);
3707 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003708 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003709
Douglas Gregor66992202010-06-29 17:53:46 +00003710 if (R.empty()) {
3711 // Allow "using namespace std;" or "using namespace ::std;" even if
3712 // "std" hasn't been defined yet, for GCC compatibility.
3713 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3714 NamespcName->isStr("std")) {
3715 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003716 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003717 R.resolveKind();
3718 }
3719 // Otherwise, attempt typo correction.
3720 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3721 CTC_NoKeywords, 0)) {
3722 if (R.getAsSingle<NamespaceDecl>() ||
3723 R.getAsSingle<NamespaceAliasDecl>()) {
3724 if (DeclContext *DC = computeDeclContext(SS, false))
3725 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3726 << NamespcName << DC << Corrected << SS.getRange()
3727 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3728 else
3729 Diag(IdentLoc, diag::err_using_directive_suggest)
3730 << NamespcName << Corrected
3731 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3732 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3733 << Corrected;
3734
3735 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003736 } else {
3737 R.clear();
3738 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003739 }
3740 }
3741 }
3742
John McCallf36e02d2009-10-09 21:13:30 +00003743 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003744 NamedDecl *Named = R.getFoundDecl();
3745 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3746 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003747 // C++ [namespace.udir]p1:
3748 // A using-directive specifies that the names in the nominated
3749 // namespace can be used in the scope in which the
3750 // using-directive appears after the using-directive. During
3751 // unqualified name lookup (3.4.1), the names appear as if they
3752 // were declared in the nearest enclosing namespace which
3753 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003754 // namespace. [Note: in this context, "contains" means "contains
3755 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003756
3757 // Find enclosing context containing both using-directive and
3758 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003759 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003760 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3761 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3762 CommonAncestor = CommonAncestor->getParent();
3763
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003764 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003765 SS.getRange(),
3766 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003767 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003768 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003769 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003770 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003771 }
3772
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003773 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003774 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003775}
3776
3777void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3778 // If scope has associated entity, then using directive is at namespace
3779 // or translation unit scope. We add UsingDirectiveDecls, into
3780 // it's lookup structure.
3781 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003782 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003783 else
3784 // Otherwise it is block-sope. using-directives will affect lookup
3785 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003786 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003787}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003788
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003789
John McCalld226f652010-08-21 09:40:31 +00003790Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003791 AccessSpecifier AS,
3792 bool HasUsingKeyword,
3793 SourceLocation UsingLoc,
3794 CXXScopeSpec &SS,
3795 UnqualifiedId &Name,
3796 AttributeList *AttrList,
3797 bool IsTypeName,
3798 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003799 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Douglas Gregor12c118a2009-11-04 16:30:06 +00003801 switch (Name.getKind()) {
3802 case UnqualifiedId::IK_Identifier:
3803 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003804 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003805 case UnqualifiedId::IK_ConversionFunctionId:
3806 break;
3807
3808 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003809 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003810 // C++0x inherited constructors.
3811 if (getLangOptions().CPlusPlus0x) break;
3812
Douglas Gregor12c118a2009-11-04 16:30:06 +00003813 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3814 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003815 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003816
3817 case UnqualifiedId::IK_DestructorName:
3818 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3819 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003820 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003821
3822 case UnqualifiedId::IK_TemplateId:
3823 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3824 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003825 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003826 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003827
3828 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3829 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003830 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003831 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003832
John McCall60fa3cf2009-12-11 02:10:03 +00003833 // Warn about using declarations.
3834 // TODO: store that the declaration was written without 'using' and
3835 // talk about access decls instead of using decls in the
3836 // diagnostics.
3837 if (!HasUsingKeyword) {
3838 UsingLoc = Name.getSourceRange().getBegin();
3839
3840 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003841 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003842 }
3843
Douglas Gregor56c04582010-12-16 00:46:58 +00003844 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3845 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3846 return 0;
3847
John McCall9488ea12009-11-17 05:59:44 +00003848 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003849 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003850 /* IsInstantiation */ false,
3851 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003852 if (UD)
3853 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003854
John McCalld226f652010-08-21 09:40:31 +00003855 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003856}
3857
Douglas Gregor09acc982010-07-07 23:08:52 +00003858/// \brief Determine whether a using declaration considers the given
3859/// declarations as "equivalent", e.g., if they are redeclarations of
3860/// the same entity or are both typedefs of the same type.
3861static bool
3862IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3863 bool &SuppressRedeclaration) {
3864 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3865 SuppressRedeclaration = false;
3866 return true;
3867 }
3868
3869 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3870 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3871 SuppressRedeclaration = true;
3872 return Context.hasSameType(TD1->getUnderlyingType(),
3873 TD2->getUnderlyingType());
3874 }
3875
3876 return false;
3877}
3878
3879
John McCall9f54ad42009-12-10 09:41:52 +00003880/// Determines whether to create a using shadow decl for a particular
3881/// decl, given the set of decls existing prior to this using lookup.
3882bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3883 const LookupResult &Previous) {
3884 // Diagnose finding a decl which is not from a base class of the
3885 // current class. We do this now because there are cases where this
3886 // function will silently decide not to build a shadow decl, which
3887 // will pre-empt further diagnostics.
3888 //
3889 // We don't need to do this in C++0x because we do the check once on
3890 // the qualifier.
3891 //
3892 // FIXME: diagnose the following if we care enough:
3893 // struct A { int foo; };
3894 // struct B : A { using A::foo; };
3895 // template <class T> struct C : A {};
3896 // template <class T> struct D : C<T> { using B::foo; } // <---
3897 // This is invalid (during instantiation) in C++03 because B::foo
3898 // resolves to the using decl in B, which is not a base class of D<T>.
3899 // We can't diagnose it immediately because C<T> is an unknown
3900 // specialization. The UsingShadowDecl in D<T> then points directly
3901 // to A::foo, which will look well-formed when we instantiate.
3902 // The right solution is to not collapse the shadow-decl chain.
3903 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3904 DeclContext *OrigDC = Orig->getDeclContext();
3905
3906 // Handle enums and anonymous structs.
3907 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3908 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3909 while (OrigRec->isAnonymousStructOrUnion())
3910 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3911
3912 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3913 if (OrigDC == CurContext) {
3914 Diag(Using->getLocation(),
3915 diag::err_using_decl_nested_name_specifier_is_current_class)
3916 << Using->getNestedNameRange();
3917 Diag(Orig->getLocation(), diag::note_using_decl_target);
3918 return true;
3919 }
3920
3921 Diag(Using->getNestedNameRange().getBegin(),
3922 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3923 << Using->getTargetNestedNameDecl()
3924 << cast<CXXRecordDecl>(CurContext)
3925 << Using->getNestedNameRange();
3926 Diag(Orig->getLocation(), diag::note_using_decl_target);
3927 return true;
3928 }
3929 }
3930
3931 if (Previous.empty()) return false;
3932
3933 NamedDecl *Target = Orig;
3934 if (isa<UsingShadowDecl>(Target))
3935 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3936
John McCalld7533ec2009-12-11 02:33:26 +00003937 // If the target happens to be one of the previous declarations, we
3938 // don't have a conflict.
3939 //
3940 // FIXME: but we might be increasing its access, in which case we
3941 // should redeclare it.
3942 NamedDecl *NonTag = 0, *Tag = 0;
3943 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3944 I != E; ++I) {
3945 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003946 bool Result;
3947 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3948 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003949
3950 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3951 }
3952
John McCall9f54ad42009-12-10 09:41:52 +00003953 if (Target->isFunctionOrFunctionTemplate()) {
3954 FunctionDecl *FD;
3955 if (isa<FunctionTemplateDecl>(Target))
3956 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3957 else
3958 FD = cast<FunctionDecl>(Target);
3959
3960 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003961 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003962 case Ovl_Overload:
3963 return false;
3964
3965 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003966 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003967 break;
3968
3969 // We found a decl with the exact signature.
3970 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003971 // If we're in a record, we want to hide the target, so we
3972 // return true (without a diagnostic) to tell the caller not to
3973 // build a shadow decl.
3974 if (CurContext->isRecord())
3975 return true;
3976
3977 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003978 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003979 break;
3980 }
3981
3982 Diag(Target->getLocation(), diag::note_using_decl_target);
3983 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3984 return true;
3985 }
3986
3987 // Target is not a function.
3988
John McCall9f54ad42009-12-10 09:41:52 +00003989 if (isa<TagDecl>(Target)) {
3990 // No conflict between a tag and a non-tag.
3991 if (!Tag) return false;
3992
John McCall41ce66f2009-12-10 19:51:03 +00003993 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003994 Diag(Target->getLocation(), diag::note_using_decl_target);
3995 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3996 return true;
3997 }
3998
3999 // No conflict between a tag and a non-tag.
4000 if (!NonTag) return false;
4001
John McCall41ce66f2009-12-10 19:51:03 +00004002 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004003 Diag(Target->getLocation(), diag::note_using_decl_target);
4004 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4005 return true;
4006}
4007
John McCall9488ea12009-11-17 05:59:44 +00004008/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004009UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004010 UsingDecl *UD,
4011 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004012
4013 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004014 NamedDecl *Target = Orig;
4015 if (isa<UsingShadowDecl>(Target)) {
4016 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4017 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004018 }
4019
4020 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004021 = UsingShadowDecl::Create(Context, CurContext,
4022 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004023 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004024
4025 Shadow->setAccess(UD->getAccess());
4026 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4027 Shadow->setInvalidDecl();
4028
John McCall9488ea12009-11-17 05:59:44 +00004029 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004030 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004031 else
John McCall604e7f12009-12-08 07:46:18 +00004032 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004033
John McCall604e7f12009-12-08 07:46:18 +00004034
John McCall9f54ad42009-12-10 09:41:52 +00004035 return Shadow;
4036}
John McCall604e7f12009-12-08 07:46:18 +00004037
John McCall9f54ad42009-12-10 09:41:52 +00004038/// Hides a using shadow declaration. This is required by the current
4039/// using-decl implementation when a resolvable using declaration in a
4040/// class is followed by a declaration which would hide or override
4041/// one or more of the using decl's targets; for example:
4042///
4043/// struct Base { void foo(int); };
4044/// struct Derived : Base {
4045/// using Base::foo;
4046/// void foo(int);
4047/// };
4048///
4049/// The governing language is C++03 [namespace.udecl]p12:
4050///
4051/// When a using-declaration brings names from a base class into a
4052/// derived class scope, member functions in the derived class
4053/// override and/or hide member functions with the same name and
4054/// parameter types in a base class (rather than conflicting).
4055///
4056/// There are two ways to implement this:
4057/// (1) optimistically create shadow decls when they're not hidden
4058/// by existing declarations, or
4059/// (2) don't create any shadow decls (or at least don't make them
4060/// visible) until we've fully parsed/instantiated the class.
4061/// The problem with (1) is that we might have to retroactively remove
4062/// a shadow decl, which requires several O(n) operations because the
4063/// decl structures are (very reasonably) not designed for removal.
4064/// (2) avoids this but is very fiddly and phase-dependent.
4065void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004066 if (Shadow->getDeclName().getNameKind() ==
4067 DeclarationName::CXXConversionFunctionName)
4068 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4069
John McCall9f54ad42009-12-10 09:41:52 +00004070 // Remove it from the DeclContext...
4071 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004072
John McCall9f54ad42009-12-10 09:41:52 +00004073 // ...and the scope, if applicable...
4074 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004075 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004076 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004077 }
4078
John McCall9f54ad42009-12-10 09:41:52 +00004079 // ...and the using decl.
4080 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4081
4082 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004083 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004084}
4085
John McCall7ba107a2009-11-18 02:36:19 +00004086/// Builds a using declaration.
4087///
4088/// \param IsInstantiation - Whether this call arises from an
4089/// instantiation of an unresolved using declaration. We treat
4090/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004091NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4092 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004093 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004094 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004095 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004096 bool IsInstantiation,
4097 bool IsTypeName,
4098 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004099 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004100 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004101 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004102
Anders Carlsson550b14b2009-08-28 05:49:21 +00004103 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004105 if (SS.isEmpty()) {
4106 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004107 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004108 }
Mike Stump1eb44332009-09-09 15:08:12 +00004109
John McCall9f54ad42009-12-10 09:41:52 +00004110 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004111 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004112 ForRedeclaration);
4113 Previous.setHideTags(false);
4114 if (S) {
4115 LookupName(Previous, S);
4116
4117 // It is really dumb that we have to do this.
4118 LookupResult::Filter F = Previous.makeFilter();
4119 while (F.hasNext()) {
4120 NamedDecl *D = F.next();
4121 if (!isDeclInScope(D, CurContext, S))
4122 F.erase();
4123 }
4124 F.done();
4125 } else {
4126 assert(IsInstantiation && "no scope in non-instantiation");
4127 assert(CurContext->isRecord() && "scope not record in instantiation");
4128 LookupQualifiedName(Previous, CurContext);
4129 }
4130
Sebastian Redlf677ea32011-02-05 19:23:19 +00004131 NestedNameSpecifier *NNS = SS.getScopeRep();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004132
John McCall9f54ad42009-12-10 09:41:52 +00004133 // Check for invalid redeclarations.
4134 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4135 return 0;
4136
4137 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004138 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4139 return 0;
4140
John McCallaf8e6ed2009-11-12 03:15:40 +00004141 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004142 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00004143 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004144 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004145 // FIXME: not all declaration name kinds are legal here
4146 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4147 UsingLoc, TypenameLoc,
4148 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004149 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004150 } else {
4151 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004152 UsingLoc, SS.getRange(),
4153 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004154 }
John McCalled976492009-12-04 22:46:56 +00004155 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004156 D = UsingDecl::Create(Context, CurContext,
4157 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00004158 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004159 }
John McCalled976492009-12-04 22:46:56 +00004160 D->setAccess(AS);
4161 CurContext->addDecl(D);
4162
4163 if (!LookupContext) return D;
4164 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004165
John McCall77bb1aa2010-05-01 00:40:08 +00004166 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004167 UD->setInvalidDecl();
4168 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004169 }
4170
Sebastian Redlf677ea32011-02-05 19:23:19 +00004171 // Constructor inheriting using decls get special treatment.
4172 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4173 if (CheckInheritedConstructorUsingDecl(UD))
4174 UD->setInvalidDecl();
4175 return UD;
4176 }
4177
4178 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004179
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004180 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004181
John McCall604e7f12009-12-08 07:46:18 +00004182 // Unlike most lookups, we don't always want to hide tag
4183 // declarations: tag names are visible through the using declaration
4184 // even if hidden by ordinary names, *except* in a dependent context
4185 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004186 if (!IsInstantiation)
4187 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004188
John McCalla24dc2e2009-11-17 02:14:36 +00004189 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004190
John McCallf36e02d2009-10-09 21:13:30 +00004191 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004192 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004193 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004194 UD->setInvalidDecl();
4195 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004196 }
4197
John McCalled976492009-12-04 22:46:56 +00004198 if (R.isAmbiguous()) {
4199 UD->setInvalidDecl();
4200 return UD;
4201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
John McCall7ba107a2009-11-18 02:36:19 +00004203 if (IsTypeName) {
4204 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004205 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004206 Diag(IdentLoc, diag::err_using_typename_non_type);
4207 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4208 Diag((*I)->getUnderlyingDecl()->getLocation(),
4209 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004210 UD->setInvalidDecl();
4211 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004212 }
4213 } else {
4214 // If we asked for a non-typename and we got a type, error out,
4215 // but only if this is an instantiation of an unresolved using
4216 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004217 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004218 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4219 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004220 UD->setInvalidDecl();
4221 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004222 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004223 }
4224
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004225 // C++0x N2914 [namespace.udecl]p6:
4226 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004227 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004228 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4229 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004230 UD->setInvalidDecl();
4231 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004232 }
Mike Stump1eb44332009-09-09 15:08:12 +00004233
John McCall9f54ad42009-12-10 09:41:52 +00004234 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4235 if (!CheckUsingShadowDecl(UD, *I, Previous))
4236 BuildUsingShadowDecl(S, UD, *I);
4237 }
John McCall9488ea12009-11-17 05:59:44 +00004238
4239 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004240}
4241
Sebastian Redlf677ea32011-02-05 19:23:19 +00004242/// Additional checks for a using declaration referring to a constructor name.
4243bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4244 if (UD->isTypeName()) {
4245 // FIXME: Cannot specify typename when specifying constructor
4246 return true;
4247 }
4248
4249 const Type *SourceType = UD->getTargetNestedNameDecl()->getAsType();
4250 assert(SourceType &&
4251 "Using decl naming constructor doesn't have type in scope spec.");
4252 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4253
4254 // Check whether the named type is a direct base class.
4255 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4256 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4257 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4258 BaseIt != BaseE; ++BaseIt) {
4259 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4260 if (CanonicalSourceType == BaseType)
4261 break;
4262 }
4263
4264 if (BaseIt == BaseE) {
4265 // Did not find SourceType in the bases.
4266 Diag(UD->getUsingLocation(),
4267 diag::err_using_decl_constructor_not_in_direct_base)
4268 << UD->getNameInfo().getSourceRange()
4269 << QualType(SourceType, 0) << TargetClass;
4270 return true;
4271 }
4272
4273 BaseIt->setInheritConstructors();
4274
4275 return false;
4276}
4277
John McCall9f54ad42009-12-10 09:41:52 +00004278/// Checks that the given using declaration is not an invalid
4279/// redeclaration. Note that this is checking only for the using decl
4280/// itself, not for any ill-formedness among the UsingShadowDecls.
4281bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4282 bool isTypeName,
4283 const CXXScopeSpec &SS,
4284 SourceLocation NameLoc,
4285 const LookupResult &Prev) {
4286 // C++03 [namespace.udecl]p8:
4287 // C++0x [namespace.udecl]p10:
4288 // A using-declaration is a declaration and can therefore be used
4289 // repeatedly where (and only where) multiple declarations are
4290 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004291 //
John McCall8a726212010-11-29 18:01:58 +00004292 // That's in non-member contexts.
4293 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004294 return false;
4295
4296 NestedNameSpecifier *Qual
4297 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4298
4299 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4300 NamedDecl *D = *I;
4301
4302 bool DTypename;
4303 NestedNameSpecifier *DQual;
4304 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4305 DTypename = UD->isTypeName();
4306 DQual = UD->getTargetNestedNameDecl();
4307 } else if (UnresolvedUsingValueDecl *UD
4308 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4309 DTypename = false;
4310 DQual = UD->getTargetNestedNameSpecifier();
4311 } else if (UnresolvedUsingTypenameDecl *UD
4312 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4313 DTypename = true;
4314 DQual = UD->getTargetNestedNameSpecifier();
4315 } else continue;
4316
4317 // using decls differ if one says 'typename' and the other doesn't.
4318 // FIXME: non-dependent using decls?
4319 if (isTypeName != DTypename) continue;
4320
4321 // using decls differ if they name different scopes (but note that
4322 // template instantiation can cause this check to trigger when it
4323 // didn't before instantiation).
4324 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4325 Context.getCanonicalNestedNameSpecifier(DQual))
4326 continue;
4327
4328 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004329 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004330 return true;
4331 }
4332
4333 return false;
4334}
4335
John McCall604e7f12009-12-08 07:46:18 +00004336
John McCalled976492009-12-04 22:46:56 +00004337/// Checks that the given nested-name qualifier used in a using decl
4338/// in the current context is appropriately related to the current
4339/// scope. If an error is found, diagnoses it and returns true.
4340bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4341 const CXXScopeSpec &SS,
4342 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004343 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004344
John McCall604e7f12009-12-08 07:46:18 +00004345 if (!CurContext->isRecord()) {
4346 // C++03 [namespace.udecl]p3:
4347 // C++0x [namespace.udecl]p8:
4348 // A using-declaration for a class member shall be a member-declaration.
4349
4350 // If we weren't able to compute a valid scope, it must be a
4351 // dependent class scope.
4352 if (!NamedContext || NamedContext->isRecord()) {
4353 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4354 << SS.getRange();
4355 return true;
4356 }
4357
4358 // Otherwise, everything is known to be fine.
4359 return false;
4360 }
4361
4362 // The current scope is a record.
4363
4364 // If the named context is dependent, we can't decide much.
4365 if (!NamedContext) {
4366 // FIXME: in C++0x, we can diagnose if we can prove that the
4367 // nested-name-specifier does not refer to a base class, which is
4368 // still possible in some cases.
4369
4370 // Otherwise we have to conservatively report that things might be
4371 // okay.
4372 return false;
4373 }
4374
4375 if (!NamedContext->isRecord()) {
4376 // Ideally this would point at the last name in the specifier,
4377 // but we don't have that level of source info.
4378 Diag(SS.getRange().getBegin(),
4379 diag::err_using_decl_nested_name_specifier_is_not_class)
4380 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4381 return true;
4382 }
4383
Douglas Gregor6fb07292010-12-21 07:41:49 +00004384 if (!NamedContext->isDependentContext() &&
4385 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4386 return true;
4387
John McCall604e7f12009-12-08 07:46:18 +00004388 if (getLangOptions().CPlusPlus0x) {
4389 // C++0x [namespace.udecl]p3:
4390 // In a using-declaration used as a member-declaration, the
4391 // nested-name-specifier shall name a base class of the class
4392 // being defined.
4393
4394 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4395 cast<CXXRecordDecl>(NamedContext))) {
4396 if (CurContext == NamedContext) {
4397 Diag(NameLoc,
4398 diag::err_using_decl_nested_name_specifier_is_current_class)
4399 << SS.getRange();
4400 return true;
4401 }
4402
4403 Diag(SS.getRange().getBegin(),
4404 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4405 << (NestedNameSpecifier*) SS.getScopeRep()
4406 << cast<CXXRecordDecl>(CurContext)
4407 << SS.getRange();
4408 return true;
4409 }
4410
4411 return false;
4412 }
4413
4414 // C++03 [namespace.udecl]p4:
4415 // A using-declaration used as a member-declaration shall refer
4416 // to a member of a base class of the class being defined [etc.].
4417
4418 // Salient point: SS doesn't have to name a base class as long as
4419 // lookup only finds members from base classes. Therefore we can
4420 // diagnose here only if we can prove that that can't happen,
4421 // i.e. if the class hierarchies provably don't intersect.
4422
4423 // TODO: it would be nice if "definitely valid" results were cached
4424 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4425 // need to be repeated.
4426
4427 struct UserData {
4428 llvm::DenseSet<const CXXRecordDecl*> Bases;
4429
4430 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4431 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4432 Data->Bases.insert(Base);
4433 return true;
4434 }
4435
4436 bool hasDependentBases(const CXXRecordDecl *Class) {
4437 return !Class->forallBases(collect, this);
4438 }
4439
4440 /// Returns true if the base is dependent or is one of the
4441 /// accumulated base classes.
4442 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4443 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4444 return !Data->Bases.count(Base);
4445 }
4446
4447 bool mightShareBases(const CXXRecordDecl *Class) {
4448 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4449 }
4450 };
4451
4452 UserData Data;
4453
4454 // Returns false if we find a dependent base.
4455 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4456 return false;
4457
4458 // Returns false if the class has a dependent base or if it or one
4459 // of its bases is present in the base set of the current context.
4460 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4461 return false;
4462
4463 Diag(SS.getRange().getBegin(),
4464 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4465 << (NestedNameSpecifier*) SS.getScopeRep()
4466 << cast<CXXRecordDecl>(CurContext)
4467 << SS.getRange();
4468
4469 return true;
John McCalled976492009-12-04 22:46:56 +00004470}
4471
John McCalld226f652010-08-21 09:40:31 +00004472Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004473 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004474 SourceLocation AliasLoc,
4475 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004476 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004477 SourceLocation IdentLoc,
4478 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004479
Anders Carlsson81c85c42009-03-28 23:53:49 +00004480 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004481 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4482 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004483
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004484 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004485 NamedDecl *PrevDecl
4486 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4487 ForRedeclaration);
4488 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4489 PrevDecl = 0;
4490
4491 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004492 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004493 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004494 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004495 // FIXME: At some point, we'll want to create the (redundant)
4496 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004497 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004498 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004499 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004500 }
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004502 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4503 diag::err_redefinition_different_kind;
4504 Diag(AliasLoc, DiagID) << Alias;
4505 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004506 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004507 }
4508
John McCalla24dc2e2009-11-17 02:14:36 +00004509 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004510 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004511
John McCallf36e02d2009-10-09 21:13:30 +00004512 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004513 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4514 CTC_NoKeywords, 0)) {
4515 if (R.getAsSingle<NamespaceDecl>() ||
4516 R.getAsSingle<NamespaceAliasDecl>()) {
4517 if (DeclContext *DC = computeDeclContext(SS, false))
4518 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4519 << Ident << DC << Corrected << SS.getRange()
4520 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4521 else
4522 Diag(IdentLoc, diag::err_using_directive_suggest)
4523 << Ident << Corrected
4524 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4525
4526 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4527 << Corrected;
4528
4529 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004530 } else {
4531 R.clear();
4532 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004533 }
4534 }
4535
4536 if (R.empty()) {
4537 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004538 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004539 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004540 }
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004542 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004543 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4544 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004545 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004546 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004547
John McCall3dbd3d52010-02-16 06:53:13 +00004548 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004549 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004550}
4551
Douglas Gregor39957dc2010-05-01 15:04:51 +00004552namespace {
4553 /// \brief Scoped object used to handle the state changes required in Sema
4554 /// to implicitly define the body of a C++ member function;
4555 class ImplicitlyDefinedFunctionScope {
4556 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004557 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004558
4559 public:
4560 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004561 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004562 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004563 S.PushFunctionScope();
4564 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4565 }
4566
4567 ~ImplicitlyDefinedFunctionScope() {
4568 S.PopExpressionEvaluationContext();
4569 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004570 }
4571 };
4572}
4573
Sebastian Redl751025d2010-09-13 22:02:47 +00004574static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4575 CXXRecordDecl *D) {
4576 ASTContext &Context = Self.Context;
4577 QualType ClassType = Context.getTypeDeclType(D);
4578 DeclarationName ConstructorName
4579 = Context.DeclarationNames.getCXXConstructorName(
4580 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4581
4582 DeclContext::lookup_const_iterator Con, ConEnd;
4583 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4584 Con != ConEnd; ++Con) {
4585 // FIXME: In C++0x, a constructor template can be a default constructor.
4586 if (isa<FunctionTemplateDecl>(*Con))
4587 continue;
4588
4589 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4590 if (Constructor->isDefaultConstructor())
4591 return Constructor;
4592 }
4593 return 0;
4594}
4595
Douglas Gregor23c94db2010-07-02 17:43:08 +00004596CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4597 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004598 // C++ [class.ctor]p5:
4599 // A default constructor for a class X is a constructor of class X
4600 // that can be called without an argument. If there is no
4601 // user-declared constructor for class X, a default constructor is
4602 // implicitly declared. An implicitly-declared default constructor
4603 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004604 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4605 "Should not build implicit default constructor!");
4606
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004607 // C++ [except.spec]p14:
4608 // An implicitly declared special member function (Clause 12) shall have an
4609 // exception-specification. [...]
4610 ImplicitExceptionSpecification ExceptSpec(Context);
4611
4612 // Direct base-class destructors.
4613 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4614 BEnd = ClassDecl->bases_end();
4615 B != BEnd; ++B) {
4616 if (B->isVirtual()) // Handled below.
4617 continue;
4618
Douglas Gregor18274032010-07-03 00:47:00 +00004619 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4620 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4621 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4622 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004623 else if (CXXConstructorDecl *Constructor
4624 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004625 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004626 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004627 }
4628
4629 // Virtual base-class destructors.
4630 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4631 BEnd = ClassDecl->vbases_end();
4632 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004633 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4634 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4635 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4636 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4637 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004638 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004639 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004640 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004641 }
4642
4643 // Field destructors.
4644 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4645 FEnd = ClassDecl->field_end();
4646 F != FEnd; ++F) {
4647 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004648 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4649 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4650 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4651 ExceptSpec.CalledDecl(
4652 DeclareImplicitDefaultConstructor(FieldClassDecl));
4653 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004654 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004655 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004656 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004657 }
John McCalle23cf432010-12-14 08:05:40 +00004658
4659 FunctionProtoType::ExtProtoInfo EPI;
4660 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4661 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4662 EPI.NumExceptions = ExceptSpec.size();
4663 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004664
4665 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004666 CanQualType ClassType
4667 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4668 DeclarationName Name
4669 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004670 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004671 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004672 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004673 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004674 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004675 /*TInfo=*/0,
4676 /*isExplicit=*/false,
4677 /*isInline=*/true,
4678 /*isImplicitlyDeclared=*/true);
4679 DefaultCon->setAccess(AS_public);
4680 DefaultCon->setImplicit();
4681 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004682
4683 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004684 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4685
Douglas Gregor23c94db2010-07-02 17:43:08 +00004686 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004687 PushOnScopeChains(DefaultCon, S, false);
4688 ClassDecl->addDecl(DefaultCon);
4689
Douglas Gregor32df23e2010-07-01 22:02:46 +00004690 return DefaultCon;
4691}
4692
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004693void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4694 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004695 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004696 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004697 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004699 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004700 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004701
Douglas Gregor39957dc2010-05-01 15:04:51 +00004702 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004703 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004704 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004705 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004706 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004707 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004708 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004709 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004710 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004711
4712 SourceLocation Loc = Constructor->getLocation();
4713 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4714
4715 Constructor->setUsed();
4716 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004717}
4718
Sebastian Redlf677ea32011-02-05 19:23:19 +00004719void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4720 // We start with an initial pass over the base classes to collect those that
4721 // inherit constructors from. If there are none, we can forgo all further
4722 // processing.
4723 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4724 BasesVector BasesToInheritFrom;
4725 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4726 BaseE = ClassDecl->bases_end();
4727 BaseIt != BaseE; ++BaseIt) {
4728 if (BaseIt->getInheritConstructors()) {
4729 QualType Base = BaseIt->getType();
4730 if (Base->isDependentType()) {
4731 // If we inherit constructors from anything that is dependent, just
4732 // abort processing altogether. We'll get another chance for the
4733 // instantiations.
4734 return;
4735 }
4736 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4737 }
4738 }
4739 if (BasesToInheritFrom.empty())
4740 return;
4741
4742 // Now collect the constructors that we already have in the current class.
4743 // Those take precedence over inherited constructors.
4744 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4745 // unless there is a user-declared constructor with the same signature in
4746 // the class where the using-declaration appears.
4747 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4748 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4749 CtorE = ClassDecl->ctor_end();
4750 CtorIt != CtorE; ++CtorIt) {
4751 ExistingConstructors.insert(
4752 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4753 }
4754
4755 Scope *S = getScopeForContext(ClassDecl);
4756 DeclarationName CreatedCtorName =
4757 Context.DeclarationNames.getCXXConstructorName(
4758 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4759
4760 // Now comes the true work.
4761 // First, we keep a map from constructor types to the base that introduced
4762 // them. Needed for finding conflicting constructors. We also keep the
4763 // actually inserted declarations in there, for pretty diagnostics.
4764 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4765 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4766 ConstructorToSourceMap InheritedConstructors;
4767 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4768 BaseE = BasesToInheritFrom.end();
4769 BaseIt != BaseE; ++BaseIt) {
4770 const RecordType *Base = *BaseIt;
4771 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4772 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4773 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4774 CtorE = BaseDecl->ctor_end();
4775 CtorIt != CtorE; ++CtorIt) {
4776 // Find the using declaration for inheriting this base's constructors.
4777 DeclarationName Name =
4778 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4779 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4780 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4781 SourceLocation UsingLoc = UD ? UD->getLocation() :
4782 ClassDecl->getLocation();
4783
4784 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4785 // from the class X named in the using-declaration consists of actual
4786 // constructors and notional constructors that result from the
4787 // transformation of defaulted parameters as follows:
4788 // - all non-template default constructors of X, and
4789 // - for each non-template constructor of X that has at least one
4790 // parameter with a default argument, the set of constructors that
4791 // results from omitting any ellipsis parameter specification and
4792 // successively omitting parameters with a default argument from the
4793 // end of the parameter-type-list.
4794 CXXConstructorDecl *BaseCtor = *CtorIt;
4795 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4796 const FunctionProtoType *BaseCtorType =
4797 BaseCtor->getType()->getAs<FunctionProtoType>();
4798
4799 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4800 maxParams = BaseCtor->getNumParams();
4801 params <= maxParams; ++params) {
4802 // Skip default constructors. They're never inherited.
4803 if (params == 0)
4804 continue;
4805 // Skip copy and move constructors for the same reason.
4806 if (CanBeCopyOrMove && params == 1)
4807 continue;
4808
4809 // Build up a function type for this particular constructor.
4810 // FIXME: The working paper does not consider that the exception spec
4811 // for the inheriting constructor might be larger than that of the
4812 // source. This code doesn't yet, either.
4813 const Type *NewCtorType;
4814 if (params == maxParams)
4815 NewCtorType = BaseCtorType;
4816 else {
4817 llvm::SmallVector<QualType, 16> Args;
4818 for (unsigned i = 0; i < params; ++i) {
4819 Args.push_back(BaseCtorType->getArgType(i));
4820 }
4821 FunctionProtoType::ExtProtoInfo ExtInfo =
4822 BaseCtorType->getExtProtoInfo();
4823 ExtInfo.Variadic = false;
4824 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4825 Args.data(), params, ExtInfo)
4826 .getTypePtr();
4827 }
4828 const Type *CanonicalNewCtorType =
4829 Context.getCanonicalType(NewCtorType);
4830
4831 // Now that we have the type, first check if the class already has a
4832 // constructor with this signature.
4833 if (ExistingConstructors.count(CanonicalNewCtorType))
4834 continue;
4835
4836 // Then we check if we have already declared an inherited constructor
4837 // with this signature.
4838 std::pair<ConstructorToSourceMap::iterator, bool> result =
4839 InheritedConstructors.insert(std::make_pair(
4840 CanonicalNewCtorType,
4841 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
4842 if (!result.second) {
4843 // Already in the map. If it came from a different class, that's an
4844 // error. Not if it's from the same.
4845 CanQualType PreviousBase = result.first->second.first;
4846 if (CanonicalBase != PreviousBase) {
4847 const CXXConstructorDecl *PrevCtor = result.first->second.second;
4848 const CXXConstructorDecl *PrevBaseCtor =
4849 PrevCtor->getInheritedConstructor();
4850 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
4851
4852 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
4853 Diag(BaseCtor->getLocation(),
4854 diag::note_using_decl_constructor_conflict_current_ctor);
4855 Diag(PrevBaseCtor->getLocation(),
4856 diag::note_using_decl_constructor_conflict_previous_ctor);
4857 Diag(PrevCtor->getLocation(),
4858 diag::note_using_decl_constructor_conflict_previous_using);
4859 }
4860 continue;
4861 }
4862
4863 // OK, we're there, now add the constructor.
4864 // C++0x [class.inhctor]p8: [...] that would be performed by a
4865 // user-writtern inline constructor [...]
4866 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
4867 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
4868 Context, ClassDecl, DNI, QualType(NewCtorType, 0), /*TInfo=*/0,
4869 BaseCtor->isExplicit(), /*Inline=*/true,
4870 /*ImplicitlyDeclared=*/true);
4871 NewCtor->setAccess(BaseCtor->getAccess());
4872
4873 // Build up the parameter decls and add them.
4874 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
4875 for (unsigned i = 0; i < params; ++i) {
4876 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, UsingLoc,
4877 /*IdentifierInfo=*/0,
4878 BaseCtorType->getArgType(i),
4879 /*TInfo=*/0, SC_None,
4880 SC_None, /*DefaultArg=*/0));
4881 }
4882 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
4883 NewCtor->setInheritedConstructor(BaseCtor);
4884
4885 PushOnScopeChains(NewCtor, S, false);
4886 ClassDecl->addDecl(NewCtor);
4887 result.first->second.second = NewCtor;
4888 }
4889 }
4890 }
4891}
4892
Douglas Gregor23c94db2010-07-02 17:43:08 +00004893CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004894 // C++ [class.dtor]p2:
4895 // If a class has no user-declared destructor, a destructor is
4896 // declared implicitly. An implicitly-declared destructor is an
4897 // inline public member of its class.
4898
4899 // C++ [except.spec]p14:
4900 // An implicitly declared special member function (Clause 12) shall have
4901 // an exception-specification.
4902 ImplicitExceptionSpecification ExceptSpec(Context);
4903
4904 // Direct base-class destructors.
4905 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4906 BEnd = ClassDecl->bases_end();
4907 B != BEnd; ++B) {
4908 if (B->isVirtual()) // Handled below.
4909 continue;
4910
4911 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4912 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004913 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004914 }
4915
4916 // Virtual base-class destructors.
4917 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4918 BEnd = ClassDecl->vbases_end();
4919 B != BEnd; ++B) {
4920 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4921 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004922 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004923 }
4924
4925 // Field destructors.
4926 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4927 FEnd = ClassDecl->field_end();
4928 F != FEnd; ++F) {
4929 if (const RecordType *RecordTy
4930 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4931 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004932 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004933 }
4934
Douglas Gregor4923aa22010-07-02 20:37:36 +00004935 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004936 FunctionProtoType::ExtProtoInfo EPI;
4937 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4938 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4939 EPI.NumExceptions = ExceptSpec.size();
4940 EPI.Exceptions = ExceptSpec.data();
4941 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004942
4943 CanQualType ClassType
4944 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4945 DeclarationName Name
4946 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004947 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004948 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004949 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004950 /*isInline=*/true,
4951 /*isImplicitlyDeclared=*/true);
4952 Destructor->setAccess(AS_public);
4953 Destructor->setImplicit();
4954 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004955
4956 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004957 ++ASTContext::NumImplicitDestructorsDeclared;
4958
4959 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004960 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004961 PushOnScopeChains(Destructor, S, false);
4962 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004963
4964 // This could be uniqued if it ever proves significant.
4965 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4966
4967 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004968
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004969 return Destructor;
4970}
4971
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004972void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004973 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004974 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004975 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004976 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004977 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004978
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004979 if (Destructor->isInvalidDecl())
4980 return;
4981
Douglas Gregor39957dc2010-05-01 15:04:51 +00004982 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004983
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004984 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004985 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4986 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004987
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004988 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004989 Diag(CurrentLocation, diag::note_member_synthesized_at)
4990 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4991
4992 Destructor->setInvalidDecl();
4993 return;
4994 }
4995
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004996 SourceLocation Loc = Destructor->getLocation();
4997 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4998
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004999 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005000 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005001}
5002
Douglas Gregor06a9f362010-05-01 20:49:11 +00005003/// \brief Builds a statement that copies the given entity from \p From to
5004/// \c To.
5005///
5006/// This routine is used to copy the members of a class with an
5007/// implicitly-declared copy assignment operator. When the entities being
5008/// copied are arrays, this routine builds for loops to copy them.
5009///
5010/// \param S The Sema object used for type-checking.
5011///
5012/// \param Loc The location where the implicit copy is being generated.
5013///
5014/// \param T The type of the expressions being copied. Both expressions must
5015/// have this type.
5016///
5017/// \param To The expression we are copying to.
5018///
5019/// \param From The expression we are copying from.
5020///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005021/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5022/// Otherwise, it's a non-static member subobject.
5023///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005024/// \param Depth Internal parameter recording the depth of the recursion.
5025///
5026/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005027static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005028BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005029 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005030 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005031 // C++0x [class.copy]p30:
5032 // Each subobject is assigned in the manner appropriate to its type:
5033 //
5034 // - if the subobject is of class type, the copy assignment operator
5035 // for the class is used (as if by explicit qualification; that is,
5036 // ignoring any possible virtual overriding functions in more derived
5037 // classes);
5038 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5039 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5040
5041 // Look for operator=.
5042 DeclarationName Name
5043 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5044 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5045 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5046
5047 // Filter out any result that isn't a copy-assignment operator.
5048 LookupResult::Filter F = OpLookup.makeFilter();
5049 while (F.hasNext()) {
5050 NamedDecl *D = F.next();
5051 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5052 if (Method->isCopyAssignmentOperator())
5053 continue;
5054
5055 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005056 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005057 F.done();
5058
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005059 // Suppress the protected check (C++ [class.protected]) for each of the
5060 // assignment operators we found. This strange dance is required when
5061 // we're assigning via a base classes's copy-assignment operator. To
5062 // ensure that we're getting the right base class subobject (without
5063 // ambiguities), we need to cast "this" to that subobject type; to
5064 // ensure that we don't go through the virtual call mechanism, we need
5065 // to qualify the operator= name with the base class (see below). However,
5066 // this means that if the base class has a protected copy assignment
5067 // operator, the protected member access check will fail. So, we
5068 // rewrite "protected" access to "public" access in this case, since we
5069 // know by construction that we're calling from a derived class.
5070 if (CopyingBaseSubobject) {
5071 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5072 L != LEnd; ++L) {
5073 if (L.getAccess() == AS_protected)
5074 L.setAccess(AS_public);
5075 }
5076 }
5077
Douglas Gregor06a9f362010-05-01 20:49:11 +00005078 // Create the nested-name-specifier that will be used to qualify the
5079 // reference to operator=; this is required to suppress the virtual
5080 // call mechanism.
5081 CXXScopeSpec SS;
5082 SS.setRange(Loc);
5083 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
5084 T.getTypePtr()));
5085
5086 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005087 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005088 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005089 /*FirstQualifierInScope=*/0, OpLookup,
5090 /*TemplateArgs=*/0,
5091 /*SuppressQualifierCheck=*/true);
5092 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005093 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005094
5095 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005096
John McCall60d7b3a2010-08-24 06:29:42 +00005097 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005098 OpEqualRef.takeAs<Expr>(),
5099 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005100 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005101 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005102
5103 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005104 }
John McCallb0207482010-03-16 06:11:48 +00005105
Douglas Gregor06a9f362010-05-01 20:49:11 +00005106 // - if the subobject is of scalar type, the built-in assignment
5107 // operator is used.
5108 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5109 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005110 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005111 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005112 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005113
5114 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005115 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005116
5117 // - if the subobject is an array, each element is assigned, in the
5118 // manner appropriate to the element type;
5119
5120 // Construct a loop over the array bounds, e.g.,
5121 //
5122 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5123 //
5124 // that will copy each of the array elements.
5125 QualType SizeType = S.Context.getSizeType();
5126
5127 // Create the iteration variable.
5128 IdentifierInfo *IterationVarName = 0;
5129 {
5130 llvm::SmallString<8> Str;
5131 llvm::raw_svector_ostream OS(Str);
5132 OS << "__i" << Depth;
5133 IterationVarName = &S.Context.Idents.get(OS.str());
5134 }
5135 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
5136 IterationVarName, SizeType,
5137 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005138 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005139
5140 // Initialize the iteration variable to zero.
5141 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005142 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005143
5144 // Create a reference to the iteration variable; we'll use this several
5145 // times throughout.
5146 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005147 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005148 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5149
5150 // Create the DeclStmt that holds the iteration variable.
5151 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5152
5153 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005154 llvm::APInt Upper
5155 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005156 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005157 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005158 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5159 BO_NE, S.Context.BoolTy,
5160 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005161
5162 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005163 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005164 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5165 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005166
5167 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005168 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5169 IterationVarRef, Loc));
5170 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5171 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005172
5173 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005174 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5175 To, From, CopyingBaseSubobject,
5176 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005177 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005178 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005179
5180 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005181 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005182 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005183 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005184 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005185}
5186
Douglas Gregora376d102010-07-02 21:50:04 +00005187/// \brief Determine whether the given class has a copy assignment operator
5188/// that accepts a const-qualified argument.
5189static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5190 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5191
5192 if (!Class->hasDeclaredCopyAssignment())
5193 S.DeclareImplicitCopyAssignment(Class);
5194
5195 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5196 DeclarationName OpName
5197 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5198
5199 DeclContext::lookup_const_iterator Op, OpEnd;
5200 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5201 // C++ [class.copy]p9:
5202 // A user-declared copy assignment operator is a non-static non-template
5203 // member function of class X with exactly one parameter of type X, X&,
5204 // const X&, volatile X& or const volatile X&.
5205 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5206 if (!Method)
5207 continue;
5208
5209 if (Method->isStatic())
5210 continue;
5211 if (Method->getPrimaryTemplate())
5212 continue;
5213 const FunctionProtoType *FnType =
5214 Method->getType()->getAs<FunctionProtoType>();
5215 assert(FnType && "Overloaded operator has no prototype.");
5216 // Don't assert on this; an invalid decl might have been left in the AST.
5217 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5218 continue;
5219 bool AcceptsConst = true;
5220 QualType ArgType = FnType->getArgType(0);
5221 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5222 ArgType = Ref->getPointeeType();
5223 // Is it a non-const lvalue reference?
5224 if (!ArgType.isConstQualified())
5225 AcceptsConst = false;
5226 }
5227 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5228 continue;
5229
5230 // We have a single argument of type cv X or cv X&, i.e. we've found the
5231 // copy assignment operator. Return whether it accepts const arguments.
5232 return AcceptsConst;
5233 }
5234 assert(Class->isInvalidDecl() &&
5235 "No copy assignment operator declared in valid code.");
5236 return false;
5237}
5238
Douglas Gregor23c94db2010-07-02 17:43:08 +00005239CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005240 // Note: The following rules are largely analoguous to the copy
5241 // constructor rules. Note that virtual bases are not taken into account
5242 // for determining the argument type of the operator. Note also that
5243 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005244
5245
Douglas Gregord3c35902010-07-01 16:36:15 +00005246 // C++ [class.copy]p10:
5247 // If the class definition does not explicitly declare a copy
5248 // assignment operator, one is declared implicitly.
5249 // The implicitly-defined copy assignment operator for a class X
5250 // will have the form
5251 //
5252 // X& X::operator=(const X&)
5253 //
5254 // if
5255 bool HasConstCopyAssignment = true;
5256
5257 // -- each direct base class B of X has a copy assignment operator
5258 // whose parameter is of type const B&, const volatile B& or B,
5259 // and
5260 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5261 BaseEnd = ClassDecl->bases_end();
5262 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5263 assert(!Base->getType()->isDependentType() &&
5264 "Cannot generate implicit members for class with dependent bases.");
5265 const CXXRecordDecl *BaseClassDecl
5266 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005267 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005268 }
5269
5270 // -- for all the nonstatic data members of X that are of a class
5271 // type M (or array thereof), each such class type has a copy
5272 // assignment operator whose parameter is of type const M&,
5273 // const volatile M& or M.
5274 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5275 FieldEnd = ClassDecl->field_end();
5276 HasConstCopyAssignment && Field != FieldEnd;
5277 ++Field) {
5278 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5279 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5280 const CXXRecordDecl *FieldClassDecl
5281 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005282 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005283 }
5284 }
5285
5286 // Otherwise, the implicitly declared copy assignment operator will
5287 // have the form
5288 //
5289 // X& X::operator=(X&)
5290 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5291 QualType RetType = Context.getLValueReferenceType(ArgType);
5292 if (HasConstCopyAssignment)
5293 ArgType = ArgType.withConst();
5294 ArgType = Context.getLValueReferenceType(ArgType);
5295
Douglas Gregorb87786f2010-07-01 17:48:08 +00005296 // C++ [except.spec]p14:
5297 // An implicitly declared special member function (Clause 12) shall have an
5298 // exception-specification. [...]
5299 ImplicitExceptionSpecification ExceptSpec(Context);
5300 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5301 BaseEnd = ClassDecl->bases_end();
5302 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005303 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005304 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005305
5306 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5307 DeclareImplicitCopyAssignment(BaseClassDecl);
5308
Douglas Gregorb87786f2010-07-01 17:48:08 +00005309 if (CXXMethodDecl *CopyAssign
5310 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5311 ExceptSpec.CalledDecl(CopyAssign);
5312 }
5313 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5314 FieldEnd = ClassDecl->field_end();
5315 Field != FieldEnd;
5316 ++Field) {
5317 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5318 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005319 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005320 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005321
5322 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5323 DeclareImplicitCopyAssignment(FieldClassDecl);
5324
Douglas Gregorb87786f2010-07-01 17:48:08 +00005325 if (CXXMethodDecl *CopyAssign
5326 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5327 ExceptSpec.CalledDecl(CopyAssign);
5328 }
5329 }
5330
Douglas Gregord3c35902010-07-01 16:36:15 +00005331 // An implicitly-declared copy assignment operator is an inline public
5332 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005333 FunctionProtoType::ExtProtoInfo EPI;
5334 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5335 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5336 EPI.NumExceptions = ExceptSpec.size();
5337 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005338 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00005339 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005340 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00005341 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005342 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005343 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005344 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00005345 /*isInline=*/true);
5346 CopyAssignment->setAccess(AS_public);
5347 CopyAssignment->setImplicit();
5348 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005349
5350 // Add the parameter to the operator.
5351 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5352 ClassDecl->getLocation(),
5353 /*Id=*/0,
5354 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005355 SC_None,
5356 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005357 CopyAssignment->setParams(&FromParam, 1);
5358
Douglas Gregora376d102010-07-02 21:50:04 +00005359 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005360 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5361
Douglas Gregor23c94db2010-07-02 17:43:08 +00005362 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005363 PushOnScopeChains(CopyAssignment, S, false);
5364 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005365
5366 AddOverriddenMethods(ClassDecl, CopyAssignment);
5367 return CopyAssignment;
5368}
5369
Douglas Gregor06a9f362010-05-01 20:49:11 +00005370void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5371 CXXMethodDecl *CopyAssignOperator) {
5372 assert((CopyAssignOperator->isImplicit() &&
5373 CopyAssignOperator->isOverloadedOperator() &&
5374 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005375 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005376 "DefineImplicitCopyAssignment called for wrong function");
5377
5378 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5379
5380 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5381 CopyAssignOperator->setInvalidDecl();
5382 return;
5383 }
5384
5385 CopyAssignOperator->setUsed();
5386
5387 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005388 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005389
5390 // C++0x [class.copy]p30:
5391 // The implicitly-defined or explicitly-defaulted copy assignment operator
5392 // for a non-union class X performs memberwise copy assignment of its
5393 // subobjects. The direct base classes of X are assigned first, in the
5394 // order of their declaration in the base-specifier-list, and then the
5395 // immediate non-static data members of X are assigned, in the order in
5396 // which they were declared in the class definition.
5397
5398 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005399 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005400
5401 // The parameter for the "other" object, which we are copying from.
5402 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5403 Qualifiers OtherQuals = Other->getType().getQualifiers();
5404 QualType OtherRefType = Other->getType();
5405 if (const LValueReferenceType *OtherRef
5406 = OtherRefType->getAs<LValueReferenceType>()) {
5407 OtherRefType = OtherRef->getPointeeType();
5408 OtherQuals = OtherRefType.getQualifiers();
5409 }
5410
5411 // Our location for everything implicitly-generated.
5412 SourceLocation Loc = CopyAssignOperator->getLocation();
5413
5414 // Construct a reference to the "other" object. We'll be using this
5415 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005416 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005417 assert(OtherRef && "Reference to parameter cannot fail!");
5418
5419 // Construct the "this" pointer. We'll be using this throughout the generated
5420 // ASTs.
5421 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5422 assert(This && "Reference to this cannot fail!");
5423
5424 // Assign base classes.
5425 bool Invalid = false;
5426 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5427 E = ClassDecl->bases_end(); Base != E; ++Base) {
5428 // Form the assignment:
5429 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5430 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005431 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005432 Invalid = true;
5433 continue;
5434 }
5435
John McCallf871d0c2010-08-07 06:22:56 +00005436 CXXCastPath BasePath;
5437 BasePath.push_back(Base);
5438
Douglas Gregor06a9f362010-05-01 20:49:11 +00005439 // Construct the "from" expression, which is an implicit cast to the
5440 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005441 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005442 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005443 CK_UncheckedDerivedToBase,
5444 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005445
5446 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005447 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005448
5449 // Implicitly cast "this" to the appropriately-qualified base type.
5450 Expr *ToE = To.takeAs<Expr>();
5451 ImpCastExprToType(ToE,
5452 Context.getCVRQualifiedType(BaseType,
5453 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005454 CK_UncheckedDerivedToBase,
5455 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005456 To = Owned(ToE);
5457
5458 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005459 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005460 To.get(), From,
5461 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005462 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005463 Diag(CurrentLocation, diag::note_member_synthesized_at)
5464 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5465 CopyAssignOperator->setInvalidDecl();
5466 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005467 }
5468
5469 // Success! Record the copy.
5470 Statements.push_back(Copy.takeAs<Expr>());
5471 }
5472
5473 // \brief Reference to the __builtin_memcpy function.
5474 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005475 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005476 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005477
5478 // Assign non-static members.
5479 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5480 FieldEnd = ClassDecl->field_end();
5481 Field != FieldEnd; ++Field) {
5482 // Check for members of reference type; we can't copy those.
5483 if (Field->getType()->isReferenceType()) {
5484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5485 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5486 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005487 Diag(CurrentLocation, diag::note_member_synthesized_at)
5488 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005489 Invalid = true;
5490 continue;
5491 }
5492
5493 // Check for members of const-qualified, non-class type.
5494 QualType BaseType = Context.getBaseElementType(Field->getType());
5495 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5496 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5497 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5498 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005499 Diag(CurrentLocation, diag::note_member_synthesized_at)
5500 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005501 Invalid = true;
5502 continue;
5503 }
5504
5505 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005506 if (FieldType->isIncompleteArrayType()) {
5507 assert(ClassDecl->hasFlexibleArrayMember() &&
5508 "Incomplete array type is not valid");
5509 continue;
5510 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005511
5512 // Build references to the field in the object we're copying from and to.
5513 CXXScopeSpec SS; // Intentionally empty
5514 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5515 LookupMemberName);
5516 MemberLookup.addDecl(*Field);
5517 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005518 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005519 Loc, /*IsArrow=*/false,
5520 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005521 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005522 Loc, /*IsArrow=*/true,
5523 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005524 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5525 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5526
5527 // If the field should be copied with __builtin_memcpy rather than via
5528 // explicit assignments, do so. This optimization only applies for arrays
5529 // of scalars and arrays of class type with trivial copy-assignment
5530 // operators.
5531 if (FieldType->isArrayType() &&
5532 (!BaseType->isRecordType() ||
5533 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5534 ->hasTrivialCopyAssignment())) {
5535 // Compute the size of the memory buffer to be copied.
5536 QualType SizeType = Context.getSizeType();
5537 llvm::APInt Size(Context.getTypeSize(SizeType),
5538 Context.getTypeSizeInChars(BaseType).getQuantity());
5539 for (const ConstantArrayType *Array
5540 = Context.getAsConstantArrayType(FieldType);
5541 Array;
5542 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005543 llvm::APInt ArraySize
5544 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005545 Size *= ArraySize;
5546 }
5547
5548 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005549 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5550 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005551
5552 bool NeedsCollectableMemCpy =
5553 (BaseType->isRecordType() &&
5554 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5555
5556 if (NeedsCollectableMemCpy) {
5557 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005558 // Create a reference to the __builtin_objc_memmove_collectable function.
5559 LookupResult R(*this,
5560 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005561 Loc, LookupOrdinaryName);
5562 LookupName(R, TUScope, true);
5563
5564 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5565 if (!CollectableMemCpy) {
5566 // Something went horribly wrong earlier, and we will have
5567 // complained about it.
5568 Invalid = true;
5569 continue;
5570 }
5571
5572 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5573 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005574 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005575 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5576 }
5577 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005578 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005579 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005580 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5581 LookupOrdinaryName);
5582 LookupName(R, TUScope, true);
5583
5584 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5585 if (!BuiltinMemCpy) {
5586 // Something went horribly wrong earlier, and we will have complained
5587 // about it.
5588 Invalid = true;
5589 continue;
5590 }
5591
5592 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5593 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005594 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005595 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5596 }
5597
John McCallca0408f2010-08-23 06:44:23 +00005598 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005599 CallArgs.push_back(To.takeAs<Expr>());
5600 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005601 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005602 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005603 if (NeedsCollectableMemCpy)
5604 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005605 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005606 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005607 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005608 else
5609 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005610 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005611 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005612 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005613
Douglas Gregor06a9f362010-05-01 20:49:11 +00005614 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5615 Statements.push_back(Call.takeAs<Expr>());
5616 continue;
5617 }
5618
5619 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005620 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005621 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005622 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005623 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005624 Diag(CurrentLocation, diag::note_member_synthesized_at)
5625 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5626 CopyAssignOperator->setInvalidDecl();
5627 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005628 }
5629
5630 // Success! Record the copy.
5631 Statements.push_back(Copy.takeAs<Stmt>());
5632 }
5633
5634 if (!Invalid) {
5635 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005636 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005637
John McCall60d7b3a2010-08-24 06:29:42 +00005638 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005639 if (Return.isInvalid())
5640 Invalid = true;
5641 else {
5642 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005643
5644 if (Trap.hasErrorOccurred()) {
5645 Diag(CurrentLocation, diag::note_member_synthesized_at)
5646 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5647 Invalid = true;
5648 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005649 }
5650 }
5651
5652 if (Invalid) {
5653 CopyAssignOperator->setInvalidDecl();
5654 return;
5655 }
5656
John McCall60d7b3a2010-08-24 06:29:42 +00005657 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005658 /*isStmtExpr=*/false);
5659 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5660 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005661}
5662
Douglas Gregor23c94db2010-07-02 17:43:08 +00005663CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5664 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005665 // C++ [class.copy]p4:
5666 // If the class definition does not explicitly declare a copy
5667 // constructor, one is declared implicitly.
5668
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005669 // C++ [class.copy]p5:
5670 // The implicitly-declared copy constructor for a class X will
5671 // have the form
5672 //
5673 // X::X(const X&)
5674 //
5675 // if
5676 bool HasConstCopyConstructor = true;
5677
5678 // -- each direct or virtual base class B of X has a copy
5679 // constructor whose first parameter is of type const B& or
5680 // const volatile B&, and
5681 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5682 BaseEnd = ClassDecl->bases_end();
5683 HasConstCopyConstructor && Base != BaseEnd;
5684 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005685 // Virtual bases are handled below.
5686 if (Base->isVirtual())
5687 continue;
5688
Douglas Gregor22584312010-07-02 23:41:54 +00005689 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005690 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005691 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5692 DeclareImplicitCopyConstructor(BaseClassDecl);
5693
Douglas Gregor598a8542010-07-01 18:27:03 +00005694 HasConstCopyConstructor
5695 = BaseClassDecl->hasConstCopyConstructor(Context);
5696 }
5697
5698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5699 BaseEnd = ClassDecl->vbases_end();
5700 HasConstCopyConstructor && Base != BaseEnd;
5701 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005702 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005703 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005704 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5705 DeclareImplicitCopyConstructor(BaseClassDecl);
5706
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005707 HasConstCopyConstructor
5708 = BaseClassDecl->hasConstCopyConstructor(Context);
5709 }
5710
5711 // -- for all the nonstatic data members of X that are of a
5712 // class type M (or array thereof), each such class type
5713 // has a copy constructor whose first parameter is of type
5714 // const M& or const volatile M&.
5715 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5716 FieldEnd = ClassDecl->field_end();
5717 HasConstCopyConstructor && Field != FieldEnd;
5718 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005719 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005720 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005721 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005722 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005723 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5724 DeclareImplicitCopyConstructor(FieldClassDecl);
5725
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005726 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005727 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005728 }
5729 }
5730
5731 // Otherwise, the implicitly declared copy constructor will have
5732 // the form
5733 //
5734 // X::X(X&)
5735 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5736 QualType ArgType = ClassType;
5737 if (HasConstCopyConstructor)
5738 ArgType = ArgType.withConst();
5739 ArgType = Context.getLValueReferenceType(ArgType);
5740
Douglas Gregor0d405db2010-07-01 20:59:04 +00005741 // C++ [except.spec]p14:
5742 // An implicitly declared special member function (Clause 12) shall have an
5743 // exception-specification. [...]
5744 ImplicitExceptionSpecification ExceptSpec(Context);
5745 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5746 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5747 BaseEnd = ClassDecl->bases_end();
5748 Base != BaseEnd;
5749 ++Base) {
5750 // Virtual bases are handled below.
5751 if (Base->isVirtual())
5752 continue;
5753
Douglas Gregor22584312010-07-02 23:41:54 +00005754 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005755 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005756 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5757 DeclareImplicitCopyConstructor(BaseClassDecl);
5758
Douglas Gregor0d405db2010-07-01 20:59:04 +00005759 if (CXXConstructorDecl *CopyConstructor
5760 = BaseClassDecl->getCopyConstructor(Context, Quals))
5761 ExceptSpec.CalledDecl(CopyConstructor);
5762 }
5763 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5764 BaseEnd = ClassDecl->vbases_end();
5765 Base != BaseEnd;
5766 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005767 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005768 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005769 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5770 DeclareImplicitCopyConstructor(BaseClassDecl);
5771
Douglas Gregor0d405db2010-07-01 20:59:04 +00005772 if (CXXConstructorDecl *CopyConstructor
5773 = BaseClassDecl->getCopyConstructor(Context, Quals))
5774 ExceptSpec.CalledDecl(CopyConstructor);
5775 }
5776 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5777 FieldEnd = ClassDecl->field_end();
5778 Field != FieldEnd;
5779 ++Field) {
5780 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5781 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005782 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005783 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005784 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5785 DeclareImplicitCopyConstructor(FieldClassDecl);
5786
Douglas Gregor0d405db2010-07-01 20:59:04 +00005787 if (CXXConstructorDecl *CopyConstructor
5788 = FieldClassDecl->getCopyConstructor(Context, Quals))
5789 ExceptSpec.CalledDecl(CopyConstructor);
5790 }
5791 }
5792
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005793 // An implicitly-declared copy constructor is an inline public
5794 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005795 FunctionProtoType::ExtProtoInfo EPI;
5796 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5797 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5798 EPI.NumExceptions = ExceptSpec.size();
5799 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005800 DeclarationName Name
5801 = Context.DeclarationNames.getCXXConstructorName(
5802 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005803 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005804 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005805 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005806 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005807 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005808 /*TInfo=*/0,
5809 /*isExplicit=*/false,
5810 /*isInline=*/true,
5811 /*isImplicitlyDeclared=*/true);
5812 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005813 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5814
Douglas Gregor22584312010-07-02 23:41:54 +00005815 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005816 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5817
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005818 // Add the parameter to the constructor.
5819 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5820 ClassDecl->getLocation(),
5821 /*IdentifierInfo=*/0,
5822 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005823 SC_None,
5824 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005825 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005826 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005827 PushOnScopeChains(CopyConstructor, S, false);
5828 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005829
5830 return CopyConstructor;
5831}
5832
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005833void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5834 CXXConstructorDecl *CopyConstructor,
5835 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005836 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005837 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005838 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005839 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005840
Anders Carlsson63010a72010-04-23 16:24:12 +00005841 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005842 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005843
Douglas Gregor39957dc2010-05-01 15:04:51 +00005844 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005845 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005846
Sean Huntcbb67482011-01-08 20:30:50 +00005847 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005848 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005849 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005850 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005851 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005852 } else {
5853 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5854 CopyConstructor->getLocation(),
5855 MultiStmtArg(*this, 0, 0),
5856 /*isStmtExpr=*/false)
5857 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005858 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005859
5860 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005861}
5862
John McCall60d7b3a2010-08-24 06:29:42 +00005863ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005864Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005865 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005866 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005867 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005868 unsigned ConstructKind,
5869 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005870 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005871
Douglas Gregor2f599792010-04-02 18:24:57 +00005872 // C++0x [class.copy]p34:
5873 // When certain criteria are met, an implementation is allowed to
5874 // omit the copy/move construction of a class object, even if the
5875 // copy/move constructor and/or destructor for the object have
5876 // side effects. [...]
5877 // - when a temporary class object that has not been bound to a
5878 // reference (12.2) would be copied/moved to a class object
5879 // with the same cv-unqualified type, the copy/move operation
5880 // can be omitted by constructing the temporary object
5881 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005882 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00005883 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005884 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005885 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005886 }
Mike Stump1eb44332009-09-09 15:08:12 +00005887
5888 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005889 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005890 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005891}
5892
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005893/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5894/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005895ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005896Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5897 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005898 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005899 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005900 unsigned ConstructKind,
5901 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005902 unsigned NumExprs = ExprArgs.size();
5903 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005904
Douglas Gregor7edfb692009-11-23 12:27:39 +00005905 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005906 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005907 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005908 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005909 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5910 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005911}
5912
Mike Stump1eb44332009-09-09 15:08:12 +00005913bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005914 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005915 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005916 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005917 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005918 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005919 move(Exprs), false, CXXConstructExpr::CK_Complete,
5920 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005921 if (TempResult.isInvalid())
5922 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005923
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005924 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005925 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005926 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005927 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005928 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005929
Anders Carlssonfe2de492009-08-25 05:18:00 +00005930 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005931}
5932
John McCall68c6c9a2010-02-02 09:10:11 +00005933void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5934 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005935 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005936 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005937 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005938 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005939 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005940 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005941 << VD->getDeclName()
5942 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005943
John McCallae792222010-09-18 05:25:11 +00005944 // TODO: this should be re-enabled for static locals by !CXAAtExit
5945 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005946 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005947 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005948}
5949
Mike Stump1eb44332009-09-09 15:08:12 +00005950/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005951/// ActOnDeclarator, when a C++ direct initializer is present.
5952/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005953void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005954 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005955 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005956 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005957 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005958
5959 // If there is no declaration, there was an error parsing it. Just ignore
5960 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005961 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005962 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005963
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005964 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5965 if (!VDecl) {
5966 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5967 RealDecl->setInvalidDecl();
5968 return;
5969 }
5970
Douglas Gregor83ddad32009-08-26 21:14:46 +00005971 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005972 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005973 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5974 //
5975 // Clients that want to distinguish between the two forms, can check for
5976 // direct initializer using VarDecl::hasCXXDirectInitializer().
5977 // A major benefit is that clients that don't particularly care about which
5978 // exactly form was it (like the CodeGen) can handle both cases without
5979 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005980
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005981 // C++ 8.5p11:
5982 // The form of initialization (using parentheses or '=') is generally
5983 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005984 // class type.
5985
Douglas Gregor4dffad62010-02-11 22:55:30 +00005986 if (!VDecl->getType()->isDependentType() &&
5987 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005988 diag::err_typecheck_decl_incomplete_type)) {
5989 VDecl->setInvalidDecl();
5990 return;
5991 }
5992
Douglas Gregor90f93822009-12-22 22:17:25 +00005993 // The variable can not have an abstract class type.
5994 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5995 diag::err_abstract_type_in_decl,
5996 AbstractVariableType))
5997 VDecl->setInvalidDecl();
5998
Sebastian Redl31310a22010-02-01 20:16:42 +00005999 const VarDecl *Def;
6000 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006001 Diag(VDecl->getLocation(), diag::err_redefinition)
6002 << VDecl->getDeclName();
6003 Diag(Def->getLocation(), diag::note_previous_definition);
6004 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006005 return;
6006 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006007
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006008 // C++ [class.static.data]p4
6009 // If a static data member is of const integral or const
6010 // enumeration type, its declaration in the class definition can
6011 // specify a constant-initializer which shall be an integral
6012 // constant expression (5.19). In that case, the member can appear
6013 // in integral constant expressions. The member shall still be
6014 // defined in a namespace scope if it is used in the program and the
6015 // namespace scope definition shall not contain an initializer.
6016 //
6017 // We already performed a redefinition check above, but for static
6018 // data members we also need to check whether there was an in-class
6019 // declaration with an initializer.
6020 const VarDecl* PrevInit = 0;
6021 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6022 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6023 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6024 return;
6025 }
6026
Douglas Gregora31040f2010-12-16 01:31:22 +00006027 bool IsDependent = false;
6028 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6029 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6030 VDecl->setInvalidDecl();
6031 return;
6032 }
6033
6034 if (Exprs.get()[I]->isTypeDependent())
6035 IsDependent = true;
6036 }
6037
Douglas Gregor4dffad62010-02-11 22:55:30 +00006038 // If either the declaration has a dependent type or if any of the
6039 // expressions is type-dependent, we represent the initialization
6040 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006041 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006042 // Let clients know that initialization was done with a direct initializer.
6043 VDecl->setCXXDirectInitializer(true);
6044
6045 // Store the initialization expressions as a ParenListExpr.
6046 unsigned NumExprs = Exprs.size();
6047 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6048 (Expr **)Exprs.release(),
6049 NumExprs, RParenLoc));
6050 return;
6051 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006052
6053 // Capture the variable that is being initialized and the style of
6054 // initialization.
6055 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6056
6057 // FIXME: Poor source location information.
6058 InitializationKind Kind
6059 = InitializationKind::CreateDirect(VDecl->getLocation(),
6060 LParenLoc, RParenLoc);
6061
6062 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006063 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006064 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006065 if (Result.isInvalid()) {
6066 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006067 return;
6068 }
John McCallb4eb64d2010-10-08 02:01:28 +00006069
6070 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006071
Douglas Gregor53c374f2010-12-07 00:41:46 +00006072 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006073 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006074 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006075
John McCall2998d6b2011-01-19 11:48:09 +00006076 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006077}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006078
Douglas Gregor39da0b82009-09-09 23:08:42 +00006079/// \brief Given a constructor and the set of arguments provided for the
6080/// constructor, convert the arguments and add any required default arguments
6081/// to form a proper call to this constructor.
6082///
6083/// \returns true if an error occurred, false otherwise.
6084bool
6085Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6086 MultiExprArg ArgsPtr,
6087 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006088 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006089 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6090 unsigned NumArgs = ArgsPtr.size();
6091 Expr **Args = (Expr **)ArgsPtr.get();
6092
6093 const FunctionProtoType *Proto
6094 = Constructor->getType()->getAs<FunctionProtoType>();
6095 assert(Proto && "Constructor without a prototype?");
6096 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006097
6098 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006099 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006100 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006101 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006102 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006103
6104 VariadicCallType CallType =
6105 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6106 llvm::SmallVector<Expr *, 8> AllArgs;
6107 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6108 Proto, 0, Args, NumArgs, AllArgs,
6109 CallType);
6110 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6111 ConvertedArgs.push_back(AllArgs[i]);
6112 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006113}
6114
Anders Carlsson20d45d22009-12-12 00:32:00 +00006115static inline bool
6116CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6117 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006118 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006119 if (isa<NamespaceDecl>(DC)) {
6120 return SemaRef.Diag(FnDecl->getLocation(),
6121 diag::err_operator_new_delete_declared_in_namespace)
6122 << FnDecl->getDeclName();
6123 }
6124
6125 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006126 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006127 return SemaRef.Diag(FnDecl->getLocation(),
6128 diag::err_operator_new_delete_declared_static)
6129 << FnDecl->getDeclName();
6130 }
6131
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006132 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006133}
6134
Anders Carlsson156c78e2009-12-13 17:53:43 +00006135static inline bool
6136CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6137 CanQualType ExpectedResultType,
6138 CanQualType ExpectedFirstParamType,
6139 unsigned DependentParamTypeDiag,
6140 unsigned InvalidParamTypeDiag) {
6141 QualType ResultType =
6142 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6143
6144 // Check that the result type is not dependent.
6145 if (ResultType->isDependentType())
6146 return SemaRef.Diag(FnDecl->getLocation(),
6147 diag::err_operator_new_delete_dependent_result_type)
6148 << FnDecl->getDeclName() << ExpectedResultType;
6149
6150 // Check that the result type is what we expect.
6151 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6152 return SemaRef.Diag(FnDecl->getLocation(),
6153 diag::err_operator_new_delete_invalid_result_type)
6154 << FnDecl->getDeclName() << ExpectedResultType;
6155
6156 // A function template must have at least 2 parameters.
6157 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6158 return SemaRef.Diag(FnDecl->getLocation(),
6159 diag::err_operator_new_delete_template_too_few_parameters)
6160 << FnDecl->getDeclName();
6161
6162 // The function decl must have at least 1 parameter.
6163 if (FnDecl->getNumParams() == 0)
6164 return SemaRef.Diag(FnDecl->getLocation(),
6165 diag::err_operator_new_delete_too_few_parameters)
6166 << FnDecl->getDeclName();
6167
6168 // Check the the first parameter type is not dependent.
6169 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6170 if (FirstParamType->isDependentType())
6171 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6172 << FnDecl->getDeclName() << ExpectedFirstParamType;
6173
6174 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006175 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006176 ExpectedFirstParamType)
6177 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6178 << FnDecl->getDeclName() << ExpectedFirstParamType;
6179
6180 return false;
6181}
6182
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006183static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006184CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006185 // C++ [basic.stc.dynamic.allocation]p1:
6186 // A program is ill-formed if an allocation function is declared in a
6187 // namespace scope other than global scope or declared static in global
6188 // scope.
6189 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6190 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006191
6192 CanQualType SizeTy =
6193 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6194
6195 // C++ [basic.stc.dynamic.allocation]p1:
6196 // The return type shall be void*. The first parameter shall have type
6197 // std::size_t.
6198 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6199 SizeTy,
6200 diag::err_operator_new_dependent_param_type,
6201 diag::err_operator_new_param_type))
6202 return true;
6203
6204 // C++ [basic.stc.dynamic.allocation]p1:
6205 // The first parameter shall not have an associated default argument.
6206 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006207 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006208 diag::err_operator_new_default_arg)
6209 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6210
6211 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006212}
6213
6214static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006215CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6216 // C++ [basic.stc.dynamic.deallocation]p1:
6217 // A program is ill-formed if deallocation functions are declared in a
6218 // namespace scope other than global scope or declared static in global
6219 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006220 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6221 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006222
6223 // C++ [basic.stc.dynamic.deallocation]p2:
6224 // Each deallocation function shall return void and its first parameter
6225 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006226 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6227 SemaRef.Context.VoidPtrTy,
6228 diag::err_operator_delete_dependent_param_type,
6229 diag::err_operator_delete_param_type))
6230 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006231
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006232 return false;
6233}
6234
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006235/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6236/// of this overloaded operator is well-formed. If so, returns false;
6237/// otherwise, emits appropriate diagnostics and returns true.
6238bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006239 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006240 "Expected an overloaded operator declaration");
6241
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006242 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6243
Mike Stump1eb44332009-09-09 15:08:12 +00006244 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006245 // The allocation and deallocation functions, operator new,
6246 // operator new[], operator delete and operator delete[], are
6247 // described completely in 3.7.3. The attributes and restrictions
6248 // found in the rest of this subclause do not apply to them unless
6249 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006250 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006251 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006252
Anders Carlssona3ccda52009-12-12 00:26:23 +00006253 if (Op == OO_New || Op == OO_Array_New)
6254 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006255
6256 // C++ [over.oper]p6:
6257 // An operator function shall either be a non-static member
6258 // function or be a non-member function and have at least one
6259 // parameter whose type is a class, a reference to a class, an
6260 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006261 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6262 if (MethodDecl->isStatic())
6263 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006264 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006265 } else {
6266 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006267 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6268 ParamEnd = FnDecl->param_end();
6269 Param != ParamEnd; ++Param) {
6270 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006271 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6272 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006273 ClassOrEnumParam = true;
6274 break;
6275 }
6276 }
6277
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006278 if (!ClassOrEnumParam)
6279 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006280 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006281 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006282 }
6283
6284 // C++ [over.oper]p8:
6285 // An operator function cannot have default arguments (8.3.6),
6286 // except where explicitly stated below.
6287 //
Mike Stump1eb44332009-09-09 15:08:12 +00006288 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006289 // (C++ [over.call]p1).
6290 if (Op != OO_Call) {
6291 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6292 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006293 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006294 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006295 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006296 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006297 }
6298 }
6299
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006300 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6301 { false, false, false }
6302#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6303 , { Unary, Binary, MemberOnly }
6304#include "clang/Basic/OperatorKinds.def"
6305 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006306
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006307 bool CanBeUnaryOperator = OperatorUses[Op][0];
6308 bool CanBeBinaryOperator = OperatorUses[Op][1];
6309 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006310
6311 // C++ [over.oper]p8:
6312 // [...] Operator functions cannot have more or fewer parameters
6313 // than the number required for the corresponding operator, as
6314 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006315 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006316 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006317 if (Op != OO_Call &&
6318 ((NumParams == 1 && !CanBeUnaryOperator) ||
6319 (NumParams == 2 && !CanBeBinaryOperator) ||
6320 (NumParams < 1) || (NumParams > 2))) {
6321 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006322 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006323 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006324 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006325 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006326 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006327 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006328 assert(CanBeBinaryOperator &&
6329 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006330 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006331 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006332
Chris Lattner416e46f2008-11-21 07:57:12 +00006333 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006334 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006335 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006336
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006337 // Overloaded operators other than operator() cannot be variadic.
6338 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006339 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006340 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006341 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006342 }
6343
6344 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006345 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6346 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006347 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006348 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006349 }
6350
6351 // C++ [over.inc]p1:
6352 // The user-defined function called operator++ implements the
6353 // prefix and postfix ++ operator. If this function is a member
6354 // function with no parameters, or a non-member function with one
6355 // parameter of class or enumeration type, it defines the prefix
6356 // increment operator ++ for objects of that type. If the function
6357 // is a member function with one parameter (which shall be of type
6358 // int) or a non-member function with two parameters (the second
6359 // of which shall be of type int), it defines the postfix
6360 // increment operator ++ for objects of that type.
6361 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6362 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6363 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006364 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006365 ParamIsInt = BT->getKind() == BuiltinType::Int;
6366
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006367 if (!ParamIsInt)
6368 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006369 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006370 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006371 }
6372
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006373 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006374}
Chris Lattner5a003a42008-12-17 07:09:26 +00006375
Sean Hunta6c058d2010-01-13 09:01:02 +00006376/// CheckLiteralOperatorDeclaration - Check whether the declaration
6377/// of this literal operator function is well-formed. If so, returns
6378/// false; otherwise, emits appropriate diagnostics and returns true.
6379bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6380 DeclContext *DC = FnDecl->getDeclContext();
6381 Decl::Kind Kind = DC->getDeclKind();
6382 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6383 Kind != Decl::LinkageSpec) {
6384 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6385 << FnDecl->getDeclName();
6386 return true;
6387 }
6388
6389 bool Valid = false;
6390
Sean Hunt216c2782010-04-07 23:11:06 +00006391 // template <char...> type operator "" name() is the only valid template
6392 // signature, and the only valid signature with no parameters.
6393 if (FnDecl->param_size() == 0) {
6394 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6395 // Must have only one template parameter
6396 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6397 if (Params->size() == 1) {
6398 NonTypeTemplateParmDecl *PmDecl =
6399 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006400
Sean Hunt216c2782010-04-07 23:11:06 +00006401 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006402 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6403 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6404 Valid = true;
6405 }
6406 }
6407 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006408 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006409 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6410
Sean Hunta6c058d2010-01-13 09:01:02 +00006411 QualType T = (*Param)->getType();
6412
Sean Hunt30019c02010-04-07 22:57:35 +00006413 // unsigned long long int, long double, and any character type are allowed
6414 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006415 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6416 Context.hasSameType(T, Context.LongDoubleTy) ||
6417 Context.hasSameType(T, Context.CharTy) ||
6418 Context.hasSameType(T, Context.WCharTy) ||
6419 Context.hasSameType(T, Context.Char16Ty) ||
6420 Context.hasSameType(T, Context.Char32Ty)) {
6421 if (++Param == FnDecl->param_end())
6422 Valid = true;
6423 goto FinishedParams;
6424 }
6425
Sean Hunt30019c02010-04-07 22:57:35 +00006426 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006427 const PointerType *PT = T->getAs<PointerType>();
6428 if (!PT)
6429 goto FinishedParams;
6430 T = PT->getPointeeType();
6431 if (!T.isConstQualified())
6432 goto FinishedParams;
6433 T = T.getUnqualifiedType();
6434
6435 // Move on to the second parameter;
6436 ++Param;
6437
6438 // If there is no second parameter, the first must be a const char *
6439 if (Param == FnDecl->param_end()) {
6440 if (Context.hasSameType(T, Context.CharTy))
6441 Valid = true;
6442 goto FinishedParams;
6443 }
6444
6445 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6446 // are allowed as the first parameter to a two-parameter function
6447 if (!(Context.hasSameType(T, Context.CharTy) ||
6448 Context.hasSameType(T, Context.WCharTy) ||
6449 Context.hasSameType(T, Context.Char16Ty) ||
6450 Context.hasSameType(T, Context.Char32Ty)))
6451 goto FinishedParams;
6452
6453 // The second and final parameter must be an std::size_t
6454 T = (*Param)->getType().getUnqualifiedType();
6455 if (Context.hasSameType(T, Context.getSizeType()) &&
6456 ++Param == FnDecl->param_end())
6457 Valid = true;
6458 }
6459
6460 // FIXME: This diagnostic is absolutely terrible.
6461FinishedParams:
6462 if (!Valid) {
6463 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6464 << FnDecl->getDeclName();
6465 return true;
6466 }
6467
6468 return false;
6469}
6470
Douglas Gregor074149e2009-01-05 19:45:36 +00006471/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6472/// linkage specification, including the language and (if present)
6473/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6474/// the location of the language string literal, which is provided
6475/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6476/// the '{' brace. Otherwise, this linkage specification does not
6477/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006478Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6479 SourceLocation LangLoc,
6480 llvm::StringRef Lang,
6481 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006482 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006483 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006484 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006485 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006486 Language = LinkageSpecDecl::lang_cxx;
6487 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006488 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006489 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006490 }
Mike Stump1eb44332009-09-09 15:08:12 +00006491
Chris Lattnercc98eac2008-12-17 07:13:27 +00006492 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006493
Douglas Gregor074149e2009-01-05 19:45:36 +00006494 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006495 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006496 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006497 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006498 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006499 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006500}
6501
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006502/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006503/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6504/// valid, it's the position of the closing '}' brace in a linkage
6505/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006506Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6507 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006508 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006509 if (LinkageSpec)
6510 PopDeclContext();
6511 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006512}
6513
Douglas Gregord308e622009-05-18 20:51:54 +00006514/// \brief Perform semantic analysis for the variable declaration that
6515/// occurs within a C++ catch clause, returning the newly-created
6516/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006517VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006518 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006519 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006520 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006521 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006522 QualType ExDeclType = TInfo->getType();
6523
Sebastian Redl4b07b292008-12-22 19:15:10 +00006524 // Arrays and functions decay.
6525 if (ExDeclType->isArrayType())
6526 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6527 else if (ExDeclType->isFunctionType())
6528 ExDeclType = Context.getPointerType(ExDeclType);
6529
6530 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6531 // The exception-declaration shall not denote a pointer or reference to an
6532 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006533 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006534 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006535 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006536 Invalid = true;
6537 }
Douglas Gregord308e622009-05-18 20:51:54 +00006538
Douglas Gregora2762912010-03-08 01:47:36 +00006539 // GCC allows catching pointers and references to incomplete types
6540 // as an extension; so do we, but we warn by default.
6541
Sebastian Redl4b07b292008-12-22 19:15:10 +00006542 QualType BaseType = ExDeclType;
6543 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006544 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006545 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006546 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006547 BaseType = Ptr->getPointeeType();
6548 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006549 DK = diag::ext_catch_incomplete_ptr;
6550 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006551 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006552 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006553 BaseType = Ref->getPointeeType();
6554 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006555 DK = diag::ext_catch_incomplete_ref;
6556 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006557 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006558 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006559 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6560 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006561 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006562
Mike Stump1eb44332009-09-09 15:08:12 +00006563 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006564 RequireNonAbstractType(Loc, ExDeclType,
6565 diag::err_abstract_type_in_decl,
6566 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006567 Invalid = true;
6568
John McCall5a180392010-07-24 00:37:23 +00006569 // Only the non-fragile NeXT runtime currently supports C++ catches
6570 // of ObjC types, and no runtime supports catching ObjC types by value.
6571 if (!Invalid && getLangOptions().ObjC1) {
6572 QualType T = ExDeclType;
6573 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6574 T = RT->getPointeeType();
6575
6576 if (T->isObjCObjectType()) {
6577 Diag(Loc, diag::err_objc_object_catch);
6578 Invalid = true;
6579 } else if (T->isObjCObjectPointerType()) {
6580 if (!getLangOptions().NeXTRuntime) {
6581 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6582 Invalid = true;
6583 } else if (!getLangOptions().ObjCNonFragileABI) {
6584 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6585 Invalid = true;
6586 }
6587 }
6588 }
6589
Mike Stump1eb44332009-09-09 15:08:12 +00006590 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006591 Name, ExDeclType, TInfo, SC_None,
6592 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006593 ExDecl->setExceptionVariable(true);
6594
Douglas Gregor6d182892010-03-05 23:38:39 +00006595 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00006596 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00006597 // C++ [except.handle]p16:
6598 // The object declared in an exception-declaration or, if the
6599 // exception-declaration does not specify a name, a temporary (12.2) is
6600 // copy-initialized (8.5) from the exception object. [...]
6601 // The object is destroyed when the handler exits, after the destruction
6602 // of any automatic objects initialized within the handler.
6603 //
6604 // We just pretend to initialize the object with itself, then make sure
6605 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00006606 QualType initType = ExDeclType;
6607
6608 InitializedEntity entity =
6609 InitializedEntity::InitializeVariable(ExDecl);
6610 InitializationKind initKind =
6611 InitializationKind::CreateCopy(Loc, SourceLocation());
6612
6613 Expr *opaqueValue =
6614 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6615 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6616 ExprResult result = sequence.Perform(*this, entity, initKind,
6617 MultiExprArg(&opaqueValue, 1));
6618 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00006619 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00006620 else {
6621 // If the constructor used was non-trivial, set this as the
6622 // "initializer".
6623 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6624 if (!construct->getConstructor()->isTrivial()) {
6625 Expr *init = MaybeCreateExprWithCleanups(construct);
6626 ExDecl->setInit(init);
6627 }
6628
6629 // And make sure it's destructable.
6630 FinalizeVarWithDestructor(ExDecl, recordType);
6631 }
Douglas Gregor6d182892010-03-05 23:38:39 +00006632 }
6633 }
6634
Douglas Gregord308e622009-05-18 20:51:54 +00006635 if (Invalid)
6636 ExDecl->setInvalidDecl();
6637
6638 return ExDecl;
6639}
6640
6641/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6642/// handler.
John McCalld226f652010-08-21 09:40:31 +00006643Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006644 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006645 bool Invalid = D.isInvalidType();
6646
6647 // Check for unexpanded parameter packs.
6648 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6649 UPPC_ExceptionType)) {
6650 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6651 D.getIdentifierLoc());
6652 Invalid = true;
6653 }
6654
Sebastian Redl4b07b292008-12-22 19:15:10 +00006655 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006656 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006657 LookupOrdinaryName,
6658 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006659 // The scope should be freshly made just for us. There is just no way
6660 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006661 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006662 if (PrevDecl->isTemplateParameter()) {
6663 // Maybe we will complain about the shadowed template parameter.
6664 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006665 }
6666 }
6667
Chris Lattnereaaebc72009-04-25 08:06:05 +00006668 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006669 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6670 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006671 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006672 }
6673
Douglas Gregor83cb9422010-09-09 17:09:21 +00006674 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006675 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006676 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006677
Chris Lattnereaaebc72009-04-25 08:06:05 +00006678 if (Invalid)
6679 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006680
Sebastian Redl4b07b292008-12-22 19:15:10 +00006681 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006682 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006683 PushOnScopeChains(ExDecl, S);
6684 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006685 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006686
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006687 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006688 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006689}
Anders Carlssonfb311762009-03-14 00:25:26 +00006690
John McCalld226f652010-08-21 09:40:31 +00006691Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006692 Expr *AssertExpr,
6693 Expr *AssertMessageExpr_) {
6694 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006695
Anders Carlssonc3082412009-03-14 00:33:21 +00006696 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6697 llvm::APSInt Value(32);
6698 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6699 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6700 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006701 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006702 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006703
Anders Carlssonc3082412009-03-14 00:33:21 +00006704 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006705 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006706 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006707 }
6708 }
Mike Stump1eb44332009-09-09 15:08:12 +00006709
Douglas Gregor399ad972010-12-15 23:55:21 +00006710 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6711 return 0;
6712
Mike Stump1eb44332009-09-09 15:08:12 +00006713 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006714 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006715
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006716 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006717 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006718}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006719
Douglas Gregor1d869352010-04-07 16:53:43 +00006720/// \brief Perform semantic analysis of the given friend type declaration.
6721///
6722/// \returns A friend declaration that.
6723FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6724 TypeSourceInfo *TSInfo) {
6725 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6726
6727 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006728 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006729
Douglas Gregor06245bf2010-04-07 17:57:12 +00006730 if (!getLangOptions().CPlusPlus0x) {
6731 // C++03 [class.friend]p2:
6732 // An elaborated-type-specifier shall be used in a friend declaration
6733 // for a class.*
6734 //
6735 // * The class-key of the elaborated-type-specifier is required.
6736 if (!ActiveTemplateInstantiations.empty()) {
6737 // Do not complain about the form of friend template types during
6738 // template instantiation; we will already have complained when the
6739 // template was declared.
6740 } else if (!T->isElaboratedTypeSpecifier()) {
6741 // If we evaluated the type to a record type, suggest putting
6742 // a tag in front.
6743 if (const RecordType *RT = T->getAs<RecordType>()) {
6744 RecordDecl *RD = RT->getDecl();
6745
6746 std::string InsertionText = std::string(" ") + RD->getKindName();
6747
6748 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6749 << (unsigned) RD->getTagKind()
6750 << T
6751 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6752 InsertionText);
6753 } else {
6754 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6755 << T
6756 << SourceRange(FriendLoc, TypeRange.getEnd());
6757 }
6758 } else if (T->getAs<EnumType>()) {
6759 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006760 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006761 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006762 }
6763 }
6764
Douglas Gregor06245bf2010-04-07 17:57:12 +00006765 // C++0x [class.friend]p3:
6766 // If the type specifier in a friend declaration designates a (possibly
6767 // cv-qualified) class type, that class is declared as a friend; otherwise,
6768 // the friend declaration is ignored.
6769
6770 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6771 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006772
6773 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6774}
6775
John McCall9a34edb2010-10-19 01:40:49 +00006776/// Handle a friend tag declaration where the scope specifier was
6777/// templated.
6778Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6779 unsigned TagSpec, SourceLocation TagLoc,
6780 CXXScopeSpec &SS,
6781 IdentifierInfo *Name, SourceLocation NameLoc,
6782 AttributeList *Attr,
6783 MultiTemplateParamsArg TempParamLists) {
6784 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6785
6786 bool isExplicitSpecialization = false;
6787 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6788 bool Invalid = false;
6789
6790 if (TemplateParameterList *TemplateParams
6791 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6792 TempParamLists.get(),
6793 TempParamLists.size(),
6794 /*friend*/ true,
6795 isExplicitSpecialization,
6796 Invalid)) {
6797 --NumMatchedTemplateParamLists;
6798
6799 if (TemplateParams->size() > 0) {
6800 // This is a declaration of a class template.
6801 if (Invalid)
6802 return 0;
6803
6804 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6805 SS, Name, NameLoc, Attr,
6806 TemplateParams, AS_public).take();
6807 } else {
6808 // The "template<>" header is extraneous.
6809 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6810 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6811 isExplicitSpecialization = true;
6812 }
6813 }
6814
6815 if (Invalid) return 0;
6816
6817 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6818
6819 bool isAllExplicitSpecializations = true;
6820 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6821 if (TempParamLists.get()[I]->size()) {
6822 isAllExplicitSpecializations = false;
6823 break;
6824 }
6825 }
6826
6827 // FIXME: don't ignore attributes.
6828
6829 // If it's explicit specializations all the way down, just forget
6830 // about the template header and build an appropriate non-templated
6831 // friend. TODO: for source fidelity, remember the headers.
6832 if (isAllExplicitSpecializations) {
6833 ElaboratedTypeKeyword Keyword
6834 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6835 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6836 TagLoc, SS.getRange(), NameLoc);
6837 if (T.isNull())
6838 return 0;
6839
6840 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6841 if (isa<DependentNameType>(T)) {
6842 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6843 TL.setKeywordLoc(TagLoc);
6844 TL.setQualifierRange(SS.getRange());
6845 TL.setNameLoc(NameLoc);
6846 } else {
6847 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6848 TL.setKeywordLoc(TagLoc);
6849 TL.setQualifierRange(SS.getRange());
6850 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6851 }
6852
6853 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6854 TSI, FriendLoc);
6855 Friend->setAccess(AS_public);
6856 CurContext->addDecl(Friend);
6857 return Friend;
6858 }
6859
6860 // Handle the case of a templated-scope friend class. e.g.
6861 // template <class T> class A<T>::B;
6862 // FIXME: we don't support these right now.
6863 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6864 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6865 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6866 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6867 TL.setKeywordLoc(TagLoc);
6868 TL.setQualifierRange(SS.getRange());
6869 TL.setNameLoc(NameLoc);
6870
6871 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6872 TSI, FriendLoc);
6873 Friend->setAccess(AS_public);
6874 Friend->setUnsupportedFriend(true);
6875 CurContext->addDecl(Friend);
6876 return Friend;
6877}
6878
6879
John McCalldd4a3b02009-09-16 22:47:08 +00006880/// Handle a friend type declaration. This works in tandem with
6881/// ActOnTag.
6882///
6883/// Notes on friend class templates:
6884///
6885/// We generally treat friend class declarations as if they were
6886/// declaring a class. So, for example, the elaborated type specifier
6887/// in a friend declaration is required to obey the restrictions of a
6888/// class-head (i.e. no typedefs in the scope chain), template
6889/// parameters are required to match up with simple template-ids, &c.
6890/// However, unlike when declaring a template specialization, it's
6891/// okay to refer to a template specialization without an empty
6892/// template parameter declaration, e.g.
6893/// friend class A<T>::B<unsigned>;
6894/// We permit this as a special case; if there are any template
6895/// parameters present at all, require proper matching, i.e.
6896/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006897Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006898 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006899 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006900
6901 assert(DS.isFriendSpecified());
6902 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6903
John McCalldd4a3b02009-09-16 22:47:08 +00006904 // Try to convert the decl specifier to a type. This works for
6905 // friend templates because ActOnTag never produces a ClassTemplateDecl
6906 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006907 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006908 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6909 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006910 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006911 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006912
Douglas Gregor6ccab972010-12-16 01:14:37 +00006913 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6914 return 0;
6915
John McCalldd4a3b02009-09-16 22:47:08 +00006916 // This is definitely an error in C++98. It's probably meant to
6917 // be forbidden in C++0x, too, but the specification is just
6918 // poorly written.
6919 //
6920 // The problem is with declarations like the following:
6921 // template <T> friend A<T>::foo;
6922 // where deciding whether a class C is a friend or not now hinges
6923 // on whether there exists an instantiation of A that causes
6924 // 'foo' to equal C. There are restrictions on class-heads
6925 // (which we declare (by fiat) elaborated friend declarations to
6926 // be) that makes this tractable.
6927 //
6928 // FIXME: handle "template <> friend class A<T>;", which
6929 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006930 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006931 Diag(Loc, diag::err_tagless_friend_type_template)
6932 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006933 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006934 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006935
John McCall02cace72009-08-28 07:59:38 +00006936 // C++98 [class.friend]p1: A friend of a class is a function
6937 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006938 // This is fixed in DR77, which just barely didn't make the C++03
6939 // deadline. It's also a very silly restriction that seriously
6940 // affects inner classes and which nobody else seems to implement;
6941 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006942 //
6943 // But note that we could warn about it: it's always useless to
6944 // friend one of your own members (it's not, however, worthless to
6945 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006946
John McCalldd4a3b02009-09-16 22:47:08 +00006947 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006948 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006949 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006950 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006951 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006952 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006953 DS.getFriendSpecLoc());
6954 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006955 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6956
6957 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006958 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006959
John McCalldd4a3b02009-09-16 22:47:08 +00006960 D->setAccess(AS_public);
6961 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006962
John McCalld226f652010-08-21 09:40:31 +00006963 return D;
John McCall02cace72009-08-28 07:59:38 +00006964}
6965
John McCall337ec3d2010-10-12 23:13:28 +00006966Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6967 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006968 const DeclSpec &DS = D.getDeclSpec();
6969
6970 assert(DS.isFriendSpecified());
6971 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6972
6973 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006974 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6975 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006976
6977 // C++ [class.friend]p1
6978 // A friend of a class is a function or class....
6979 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006980 // It *doesn't* see through dependent types, which is correct
6981 // according to [temp.arg.type]p3:
6982 // If a declaration acquires a function type through a
6983 // type dependent on a template-parameter and this causes
6984 // a declaration that does not use the syntactic form of a
6985 // function declarator to have a function type, the program
6986 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006987 if (!T->isFunctionType()) {
6988 Diag(Loc, diag::err_unexpected_friend);
6989
6990 // It might be worthwhile to try to recover by creating an
6991 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006992 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006993 }
6994
6995 // C++ [namespace.memdef]p3
6996 // - If a friend declaration in a non-local class first declares a
6997 // class or function, the friend class or function is a member
6998 // of the innermost enclosing namespace.
6999 // - The name of the friend is not found by simple name lookup
7000 // until a matching declaration is provided in that namespace
7001 // scope (either before or after the class declaration granting
7002 // friendship).
7003 // - If a friend function is called, its name may be found by the
7004 // name lookup that considers functions from namespaces and
7005 // classes associated with the types of the function arguments.
7006 // - When looking for a prior declaration of a class or a function
7007 // declared as a friend, scopes outside the innermost enclosing
7008 // namespace scope are not considered.
7009
John McCall337ec3d2010-10-12 23:13:28 +00007010 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007011 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7012 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007013 assert(Name);
7014
Douglas Gregor6ccab972010-12-16 01:14:37 +00007015 // Check for unexpanded parameter packs.
7016 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7017 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7018 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7019 return 0;
7020
John McCall67d1a672009-08-06 02:15:43 +00007021 // The context we found the declaration in, or in which we should
7022 // create the declaration.
7023 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007024 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007025 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007026 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007027
John McCall337ec3d2010-10-12 23:13:28 +00007028 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007029
John McCall337ec3d2010-10-12 23:13:28 +00007030 // There are four cases here.
7031 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007032 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007033 // there as appropriate.
7034 // Recover from invalid scope qualifiers as if they just weren't there.
7035 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007036 // C++0x [namespace.memdef]p3:
7037 // If the name in a friend declaration is neither qualified nor
7038 // a template-id and the declaration is a function or an
7039 // elaborated-type-specifier, the lookup to determine whether
7040 // the entity has been previously declared shall not consider
7041 // any scopes outside the innermost enclosing namespace.
7042 // C++0x [class.friend]p11:
7043 // If a friend declaration appears in a local class and the name
7044 // specified is an unqualified name, a prior declaration is
7045 // looked up without considering scopes that are outside the
7046 // innermost enclosing non-class scope. For a friend function
7047 // declaration, if there is no prior declaration, the program is
7048 // ill-formed.
7049 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007050 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007051
John McCall29ae6e52010-10-13 05:45:15 +00007052 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007053 DC = CurContext;
7054 while (true) {
7055 // Skip class contexts. If someone can cite chapter and verse
7056 // for this behavior, that would be nice --- it's what GCC and
7057 // EDG do, and it seems like a reasonable intent, but the spec
7058 // really only says that checks for unqualified existing
7059 // declarations should stop at the nearest enclosing namespace,
7060 // not that they should only consider the nearest enclosing
7061 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007062 while (DC->isRecord())
7063 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007064
John McCall68263142009-11-18 22:49:29 +00007065 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007066
7067 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007068 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007069 break;
John McCall29ae6e52010-10-13 05:45:15 +00007070
John McCall8a407372010-10-14 22:22:28 +00007071 if (isTemplateId) {
7072 if (isa<TranslationUnitDecl>(DC)) break;
7073 } else {
7074 if (DC->isFileContext()) break;
7075 }
John McCall67d1a672009-08-06 02:15:43 +00007076 DC = DC->getParent();
7077 }
7078
7079 // C++ [class.friend]p1: A friend of a class is a function or
7080 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007081 // C++0x changes this for both friend types and functions.
7082 // Most C++ 98 compilers do seem to give an error here, so
7083 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007084 if (!Previous.empty() && DC->Equals(CurContext)
7085 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007086 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007087
John McCall380aaa42010-10-13 06:22:15 +00007088 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007089
John McCall337ec3d2010-10-12 23:13:28 +00007090 // - There's a non-dependent scope specifier, in which case we
7091 // compute it and do a previous lookup there for a function
7092 // or function template.
7093 } else if (!SS.getScopeRep()->isDependent()) {
7094 DC = computeDeclContext(SS);
7095 if (!DC) return 0;
7096
7097 if (RequireCompleteDeclContext(SS, DC)) return 0;
7098
7099 LookupQualifiedName(Previous, DC);
7100
7101 // Ignore things found implicitly in the wrong scope.
7102 // TODO: better diagnostics for this case. Suggesting the right
7103 // qualified scope would be nice...
7104 LookupResult::Filter F = Previous.makeFilter();
7105 while (F.hasNext()) {
7106 NamedDecl *D = F.next();
7107 if (!DC->InEnclosingNamespaceSetOf(
7108 D->getDeclContext()->getRedeclContext()))
7109 F.erase();
7110 }
7111 F.done();
7112
7113 if (Previous.empty()) {
7114 D.setInvalidType();
7115 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7116 return 0;
7117 }
7118
7119 // C++ [class.friend]p1: A friend of a class is a function or
7120 // class that is not a member of the class . . .
7121 if (DC->Equals(CurContext))
7122 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7123
7124 // - There's a scope specifier that does not match any template
7125 // parameter lists, in which case we use some arbitrary context,
7126 // create a method or method template, and wait for instantiation.
7127 // - There's a scope specifier that does match some template
7128 // parameter lists, which we don't handle right now.
7129 } else {
7130 DC = CurContext;
7131 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007132 }
7133
John McCall29ae6e52010-10-13 05:45:15 +00007134 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007135 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007136 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7137 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7138 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007139 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007140 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7141 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007142 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007143 }
John McCall67d1a672009-08-06 02:15:43 +00007144 }
7145
Douglas Gregor182ddf02009-09-28 00:08:27 +00007146 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007147 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007148 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007149 IsDefinition,
7150 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007151 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007152
Douglas Gregor182ddf02009-09-28 00:08:27 +00007153 assert(ND->getDeclContext() == DC);
7154 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007155
John McCallab88d972009-08-31 22:39:49 +00007156 // Add the function declaration to the appropriate lookup tables,
7157 // adjusting the redeclarations list as necessary. We don't
7158 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007159 //
John McCallab88d972009-08-31 22:39:49 +00007160 // Also update the scope-based lookup if the target context's
7161 // lookup context is in lexical scope.
7162 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007163 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007164 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007165 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007166 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007167 }
John McCall02cace72009-08-28 07:59:38 +00007168
7169 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007170 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007171 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007172 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007173 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007174
John McCall337ec3d2010-10-12 23:13:28 +00007175 if (ND->isInvalidDecl())
7176 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007177 else {
7178 FunctionDecl *FD;
7179 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7180 FD = FTD->getTemplatedDecl();
7181 else
7182 FD = cast<FunctionDecl>(ND);
7183
7184 // Mark templated-scope function declarations as unsupported.
7185 if (FD->getNumTemplateParameterLists())
7186 FrD->setUnsupportedFriend(true);
7187 }
John McCall337ec3d2010-10-12 23:13:28 +00007188
John McCalld226f652010-08-21 09:40:31 +00007189 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007190}
7191
John McCalld226f652010-08-21 09:40:31 +00007192void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7193 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007194
Sebastian Redl50de12f2009-03-24 22:27:57 +00007195 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7196 if (!Fn) {
7197 Diag(DelLoc, diag::err_deleted_non_function);
7198 return;
7199 }
7200 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7201 Diag(DelLoc, diag::err_deleted_decl_not_first);
7202 Diag(Prev->getLocation(), diag::note_previous_declaration);
7203 // If the declaration wasn't the first, we delete the function anyway for
7204 // recovery.
7205 }
7206 Fn->setDeleted();
7207}
Sebastian Redl13e88542009-04-27 21:33:24 +00007208
7209static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007210 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007211 Stmt *SubStmt = *CI;
7212 if (!SubStmt)
7213 continue;
7214 if (isa<ReturnStmt>(SubStmt))
7215 Self.Diag(SubStmt->getSourceRange().getBegin(),
7216 diag::err_return_in_constructor_handler);
7217 if (!isa<Expr>(SubStmt))
7218 SearchForReturnInStmt(Self, SubStmt);
7219 }
7220}
7221
7222void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7223 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7224 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7225 SearchForReturnInStmt(*this, Handler);
7226 }
7227}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007228
Mike Stump1eb44332009-09-09 15:08:12 +00007229bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007230 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007231 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7232 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007233
Chandler Carruth73857792010-02-15 11:53:20 +00007234 if (Context.hasSameType(NewTy, OldTy) ||
7235 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007237
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007238 // Check if the return types are covariant
7239 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007240
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007241 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007242 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7243 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007244 NewClassTy = NewPT->getPointeeType();
7245 OldClassTy = OldPT->getPointeeType();
7246 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007247 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7248 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7249 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7250 NewClassTy = NewRT->getPointeeType();
7251 OldClassTy = OldRT->getPointeeType();
7252 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007253 }
7254 }
Mike Stump1eb44332009-09-09 15:08:12 +00007255
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007256 // The return types aren't either both pointers or references to a class type.
7257 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007258 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007259 diag::err_different_return_type_for_overriding_virtual_function)
7260 << New->getDeclName() << NewTy << OldTy;
7261 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007262
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007263 return true;
7264 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007265
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007266 // C++ [class.virtual]p6:
7267 // If the return type of D::f differs from the return type of B::f, the
7268 // class type in the return type of D::f shall be complete at the point of
7269 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007270 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7271 if (!RT->isBeingDefined() &&
7272 RequireCompleteType(New->getLocation(), NewClassTy,
7273 PDiag(diag::err_covariant_return_incomplete)
7274 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007275 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007276 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007277
Douglas Gregora4923eb2009-11-16 21:35:15 +00007278 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007279 // Check if the new class derives from the old class.
7280 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7281 Diag(New->getLocation(),
7282 diag::err_covariant_return_not_derived)
7283 << New->getDeclName() << NewTy << OldTy;
7284 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7285 return true;
7286 }
Mike Stump1eb44332009-09-09 15:08:12 +00007287
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007288 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007289 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007290 diag::err_covariant_return_inaccessible_base,
7291 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7292 // FIXME: Should this point to the return type?
7293 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007294 // FIXME: this note won't trigger for delayed access control
7295 // diagnostics, and it's impossible to get an undelayed error
7296 // here from access control during the original parse because
7297 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007298 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7299 return true;
7300 }
7301 }
Mike Stump1eb44332009-09-09 15:08:12 +00007302
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007303 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007304 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007305 Diag(New->getLocation(),
7306 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007307 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007308 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7309 return true;
7310 };
Mike Stump1eb44332009-09-09 15:08:12 +00007311
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007312
7313 // The new class type must have the same or less qualifiers as the old type.
7314 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7315 Diag(New->getLocation(),
7316 diag::err_covariant_return_type_class_type_more_qualified)
7317 << New->getDeclName() << NewTy << OldTy;
7318 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7319 return true;
7320 };
Mike Stump1eb44332009-09-09 15:08:12 +00007321
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007322 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007323}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007324
Douglas Gregor4ba31362009-12-01 17:24:26 +00007325/// \brief Mark the given method pure.
7326///
7327/// \param Method the method to be marked pure.
7328///
7329/// \param InitRange the source range that covers the "0" initializer.
7330bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7331 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7332 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007333 return false;
7334 }
7335
7336 if (!Method->isInvalidDecl())
7337 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7338 << Method->getDeclName() << InitRange;
7339 return true;
7340}
7341
John McCall731ad842009-12-19 09:28:58 +00007342/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7343/// an initializer for the out-of-line declaration 'Dcl'. The scope
7344/// is a fresh scope pushed for just this purpose.
7345///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007346/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7347/// static data member of class X, names should be looked up in the scope of
7348/// class X.
John McCalld226f652010-08-21 09:40:31 +00007349void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007350 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007351 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007352
John McCall731ad842009-12-19 09:28:58 +00007353 // We should only get called for declarations with scope specifiers, like:
7354 // int foo::bar;
7355 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007356 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007357}
7358
7359/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007360/// initializer for the out-of-line declaration 'D'.
7361void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007362 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007363 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007364
John McCall731ad842009-12-19 09:28:58 +00007365 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007366 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007367}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007368
7369/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7370/// C++ if/switch/while/for statement.
7371/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007372DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007373 // C++ 6.4p2:
7374 // The declarator shall not specify a function or an array.
7375 // The type-specifier-seq shall not contain typedef and shall not declare a
7376 // new class or enumeration.
7377 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7378 "Parser allowed 'typedef' as storage class of condition decl.");
7379
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007380 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007381 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7382 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007383
7384 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7385 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7386 // would be created and CXXConditionDeclExpr wants a VarDecl.
7387 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7388 << D.getSourceRange();
7389 return DeclResult();
7390 } else if (OwnedTag && OwnedTag->isDefinition()) {
7391 // The type-specifier-seq shall not declare a new class or enumeration.
7392 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7393 }
7394
John McCalld226f652010-08-21 09:40:31 +00007395 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007396 if (!Dcl)
7397 return DeclResult();
7398
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007399 return Dcl;
7400}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007401
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007402void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7403 bool DefinitionRequired) {
7404 // Ignore any vtable uses in unevaluated operands or for classes that do
7405 // not have a vtable.
7406 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7407 CurContext->isDependentContext() ||
7408 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007409 return;
7410
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007411 // Try to insert this class into the map.
7412 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7413 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7414 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7415 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007416 // If we already had an entry, check to see if we are promoting this vtable
7417 // to required a definition. If so, we need to reappend to the VTableUses
7418 // list, since we may have already processed the first entry.
7419 if (DefinitionRequired && !Pos.first->second) {
7420 Pos.first->second = true;
7421 } else {
7422 // Otherwise, we can early exit.
7423 return;
7424 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007425 }
7426
7427 // Local classes need to have their virtual members marked
7428 // immediately. For all other classes, we mark their virtual members
7429 // at the end of the translation unit.
7430 if (Class->isLocalClass())
7431 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007432 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007433 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007434}
7435
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007436bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007437 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007438 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007439
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007440 // Note: The VTableUses vector could grow as a result of marking
7441 // the members of a class as "used", so we check the size each
7442 // time through the loop and prefer indices (with are stable) to
7443 // iterators (which are not).
7444 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007445 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007446 if (!Class)
7447 continue;
7448
7449 SourceLocation Loc = VTableUses[I].second;
7450
7451 // If this class has a key function, but that key function is
7452 // defined in another translation unit, we don't need to emit the
7453 // vtable even though we're using it.
7454 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007455 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007456 switch (KeyFunction->getTemplateSpecializationKind()) {
7457 case TSK_Undeclared:
7458 case TSK_ExplicitSpecialization:
7459 case TSK_ExplicitInstantiationDeclaration:
7460 // The key function is in another translation unit.
7461 continue;
7462
7463 case TSK_ExplicitInstantiationDefinition:
7464 case TSK_ImplicitInstantiation:
7465 // We will be instantiating the key function.
7466 break;
7467 }
7468 } else if (!KeyFunction) {
7469 // If we have a class with no key function that is the subject
7470 // of an explicit instantiation declaration, suppress the
7471 // vtable; it will live with the explicit instantiation
7472 // definition.
7473 bool IsExplicitInstantiationDeclaration
7474 = Class->getTemplateSpecializationKind()
7475 == TSK_ExplicitInstantiationDeclaration;
7476 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7477 REnd = Class->redecls_end();
7478 R != REnd; ++R) {
7479 TemplateSpecializationKind TSK
7480 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7481 if (TSK == TSK_ExplicitInstantiationDeclaration)
7482 IsExplicitInstantiationDeclaration = true;
7483 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7484 IsExplicitInstantiationDeclaration = false;
7485 break;
7486 }
7487 }
7488
7489 if (IsExplicitInstantiationDeclaration)
7490 continue;
7491 }
7492
7493 // Mark all of the virtual members of this class as referenced, so
7494 // that we can build a vtable. Then, tell the AST consumer that a
7495 // vtable for this class is required.
7496 MarkVirtualMembersReferenced(Loc, Class);
7497 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7498 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7499
7500 // Optionally warn if we're emitting a weak vtable.
7501 if (Class->getLinkage() == ExternalLinkage &&
7502 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007503 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007504 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7505 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007506 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007507 VTableUses.clear();
7508
Anders Carlssond6a637f2009-12-07 08:24:59 +00007509 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007510}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007511
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007512void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7513 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007514 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7515 e = RD->method_end(); i != e; ++i) {
7516 CXXMethodDecl *MD = *i;
7517
7518 // C++ [basic.def.odr]p2:
7519 // [...] A virtual member function is used if it is not pure. [...]
7520 if (MD->isVirtual() && !MD->isPure())
7521 MarkDeclarationReferenced(Loc, MD);
7522 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007523
7524 // Only classes that have virtual bases need a VTT.
7525 if (RD->getNumVBases() == 0)
7526 return;
7527
7528 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7529 e = RD->bases_end(); i != e; ++i) {
7530 const CXXRecordDecl *Base =
7531 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007532 if (Base->getNumVBases() == 0)
7533 continue;
7534 MarkVirtualMembersReferenced(Loc, Base);
7535 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007536}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007537
7538/// SetIvarInitializers - This routine builds initialization ASTs for the
7539/// Objective-C implementation whose ivars need be initialized.
7540void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7541 if (!getLangOptions().CPlusPlus)
7542 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007543 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007544 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7545 CollectIvarsToConstructOrDestruct(OID, ivars);
7546 if (ivars.empty())
7547 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007548 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007549 for (unsigned i = 0; i < ivars.size(); i++) {
7550 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007551 if (Field->isInvalidDecl())
7552 continue;
7553
Sean Huntcbb67482011-01-08 20:30:50 +00007554 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007555 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7556 InitializationKind InitKind =
7557 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7558
7559 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007560 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007561 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007562 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007563 // Note, MemberInit could actually come back empty if no initialization
7564 // is required (e.g., because it would call a trivial default constructor)
7565 if (!MemberInit.get() || MemberInit.isInvalid())
7566 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007567
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007568 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007569 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7570 SourceLocation(),
7571 MemberInit.takeAs<Expr>(),
7572 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007573 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007574
7575 // Be sure that the destructor is accessible and is marked as referenced.
7576 if (const RecordType *RecordTy
7577 = Context.getBaseElementType(Field->getType())
7578 ->getAs<RecordType>()) {
7579 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007580 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007581 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7582 CheckDestructorAccess(Field->getLocation(), Destructor,
7583 PDiag(diag::err_access_dtor_ivar)
7584 << Context.getBaseElementType(Field->getType()));
7585 }
7586 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007587 }
7588 ObjCImplementation->setIvarInitializers(Context,
7589 AllToInit.data(), AllToInit.size());
7590 }
7591}