blob: 90ec795005ed7942b1ea3ad2fc4a9e089727956e [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000138
John McCallb4eb64d2010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson9351c172009-08-25 03:18:48 +0000157 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000158}
159
Chris Lattner8123a952008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163void
John McCalld226f652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCalld226f652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6f526752010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlsson66e30672009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump1eb44332009-09-09 15:08:12 +0000192
John McCall9ae2f072010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000194}
195
Douglas Gregor61366e92008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
John McCalld226f652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Anders Carlsson5e300d12009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000211}
212
Douglas Gregor72b505b2008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000218
John McCalld226f652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Anders Carlsson5e300d12009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Anders Carlsson5e300d12009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000224}
225
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner3d1cee32008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregor6cc15182009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCall3d6c1782010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregore13ad832010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000382
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 else
Mike Stump1eb44332009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner3d1cee32008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000437
Douglas Gregorb48fe382008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump1eb44332009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor2943aed2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000513 return 0;
John McCall572fc622010-08-17 07:23:57 +0000514 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000515
Eli Friedman1d954f62009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000523
Anders Carlssondfc2f102011-01-22 17:51:53 +0000524 // C++ [class.derived]p2:
525 // If a class is marked with the class-virt-specifier final and it appears
526 // as a base-type-specifier in a base-clause (10 class.derived), the program
527 // is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000528 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000529 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
530 << CXXBaseDecl->getDeclName();
531 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
532 << CXXBaseDecl->getDeclName();
533 return 0;
534 }
535
John McCall572fc622010-08-17 07:23:57 +0000536 if (BaseDecl->isInvalidDecl())
537 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000538
539 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000540 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000541 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000542 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000543}
544
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000545/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
546/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000547/// example:
548/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000549/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000550BaseResult
John McCalld226f652010-08-21 09:40:31 +0000551Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000552 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000553 ParsedType basetype, SourceLocation BaseLoc,
554 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000555 if (!classdecl)
556 return true;
557
Douglas Gregor40808ce2009-03-09 23:48:35 +0000558 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000559 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000560 if (!Class)
561 return true;
562
Nick Lewycky56062202010-07-26 16:56:01 +0000563 TypeSourceInfo *TInfo = 0;
564 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000565
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000566 if (EllipsisLoc.isInvalid() &&
567 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000568 UPPC_BaseType))
569 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000570
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000572 Virtual, Access, TInfo,
573 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000577}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000578
Douglas Gregor2943aed2009-03-03 04:44:36 +0000579/// \brief Performs the actual work of attaching the given base class
580/// specifiers to a C++ class.
581bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
582 unsigned NumBases) {
583 if (NumBases == 0)
584 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000585
586 // Used to keep track of which base types we have already seen, so
587 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000588 // that the key is always the unqualified canonical type of the base
589 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000590 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
591
592 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000593 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000595 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000598 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000599 if (!Class->hasObjectMember()) {
600 if (const RecordType *FDTTy =
601 NewBaseType.getTypePtr()->getAs<RecordType>())
602 if (FDTTy->getDecl()->hasObjectMember())
603 Class->setHasObjectMember(true);
604 }
605
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000606 if (KnownBaseTypes[NewBaseType]) {
607 // C++ [class.mi]p3:
608 // A class shall not be specified as a direct base class of a
609 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000610 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000611 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000612 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000614
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000617 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618
619 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 } else {
621 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000622 KnownBaseTypes[NewBaseType] = Bases[idx];
623 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000624 }
625 }
626
627 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000628 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000629
630 // Delete the remaining (good) base class specifiers, since their
631 // data has been copied into the CXXRecordDecl.
632 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000634
635 return Invalid;
636}
637
638/// ActOnBaseSpecifiers - Attach the given base specifiers to the
639/// class, after checking whether there are any duplicate base
640/// classes.
John McCalld226f652010-08-21 09:40:31 +0000641void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 unsigned NumBases) {
643 if (!ClassDecl || !Bases || !NumBases)
644 return;
645
646 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000647 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000649}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000650
John McCall3cb0ebd2010-03-10 03:28:59 +0000651static CXXRecordDecl *GetClassForType(QualType T) {
652 if (const RecordType *RT = T->getAs<RecordType>())
653 return cast<CXXRecordDecl>(RT->getDecl());
654 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
655 return ICT->getDecl();
656 else
657 return 0;
658}
659
Douglas Gregora8f32e02009-10-06 17:59:45 +0000660/// \brief Determine whether the type \p Derived is a C++ class that is
661/// derived from the type \p Base.
662bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
663 if (!getLangOptions().CPlusPlus)
664 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000665
666 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
667 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000668 return false;
669
John McCall3cb0ebd2010-03-10 03:28:59 +0000670 CXXRecordDecl *BaseRD = GetClassForType(Base);
671 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000672 return false;
673
John McCall86ff3082010-02-04 22:26:26 +0000674 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
675 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000676}
677
678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
683
John McCall3cb0ebd2010-03-10 03:28:59 +0000684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 return false;
687
John McCall3cb0ebd2010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000690 return false;
691
Douglas Gregora8f32e02009-10-06 17:59:45 +0000692 return DerivedRD->isDerivedFrom(BaseRD, Paths);
693}
694
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000695void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000696 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000697 assert(BasePathArray.empty() && "Base path array must be empty!");
698 assert(Paths.isRecordingPaths() && "Must record paths!");
699
700 const CXXBasePath &Path = Paths.front();
701
702 // We first go backward and check if we have a virtual base.
703 // FIXME: It would be better if CXXBasePath had the base specifier for
704 // the nearest virtual base.
705 unsigned Start = 0;
706 for (unsigned I = Path.size(); I != 0; --I) {
707 if (Path[I - 1].Base->isVirtual()) {
708 Start = I - 1;
709 break;
710 }
711 }
712
713 // Now add all bases.
714 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000715 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000716}
717
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000718/// \brief Determine whether the given base path includes a virtual
719/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000720bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
721 for (CXXCastPath::const_iterator B = BasePath.begin(),
722 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000723 B != BEnd; ++B)
724 if ((*B)->isVirtual())
725 return true;
726
727 return false;
728}
729
Douglas Gregora8f32e02009-10-06 17:59:45 +0000730/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
731/// conversion (where Derived and Base are class types) is
732/// well-formed, meaning that the conversion is unambiguous (and
733/// that all of the base classes are accessible). Returns true
734/// and emits a diagnostic if the code is ill-formed, returns false
735/// otherwise. Loc is the location where this routine should point to
736/// if there is an error, and Range is the source range to highlight
737/// if there is an error.
738bool
739Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000740 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000741 unsigned AmbigiousBaseConvID,
742 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000743 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000744 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000745 // First, determine whether the path from Derived to Base is
746 // ambiguous. This is slightly more expensive than checking whether
747 // the Derived to Base conversion exists, because here we need to
748 // explore multiple paths to determine if there is an ambiguity.
749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
750 /*DetectVirtual=*/false);
751 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
752 assert(DerivationOkay &&
753 "Can only be used with a derived-to-base conversion");
754 (void)DerivationOkay;
755
756 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000757 if (InaccessibleBaseID) {
758 // Check that the base class can be accessed.
759 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
760 InaccessibleBaseID)) {
761 case AR_inaccessible:
762 return true;
763 case AR_accessible:
764 case AR_dependent:
765 case AR_delayed:
766 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000767 }
John McCall6b2accb2010-02-10 09:31:12 +0000768 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000769
770 // Build a base path if necessary.
771 if (BasePath)
772 BuildBasePathArray(Paths, *BasePath);
773 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000774 }
775
776 // We know that the derived-to-base conversion is ambiguous, and
777 // we're going to produce a diagnostic. Perform the derived-to-base
778 // search just one more time to compute all of the possible paths so
779 // that we can print them out. This is more expensive than any of
780 // the previous derived-to-base checks we've done, but at this point
781 // performance isn't as much of an issue.
782 Paths.clear();
783 Paths.setRecordingPaths(true);
784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
785 assert(StillOkay && "Can only be used with a derived-to-base conversion");
786 (void)StillOkay;
787
788 // Build up a textual representation of the ambiguous paths, e.g.,
789 // D -> B -> A, that will be used to illustrate the ambiguous
790 // conversions in the diagnostic. We only print one of the paths
791 // to each base class subobject.
792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
793
794 Diag(Loc, AmbigiousBaseConvID)
795 << Derived << Base << PathDisplayStr << Range << Name;
796 return true;
797}
798
799bool
800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000801 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000802 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000803 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000804 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000805 IgnoreAccess ? 0
806 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000807 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000808 Loc, Range, DeclarationName(),
809 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000810}
811
812
813/// @brief Builds a string representing ambiguous paths from a
814/// specific derived class to different subobjects of the same base
815/// class.
816///
817/// This function builds a string that can be used in error messages
818/// to show the different paths that one can take through the
819/// inheritance hierarchy to go from the derived class to different
820/// subobjects of a base class. The result looks something like this:
821/// @code
822/// struct D -> struct B -> struct A
823/// struct D -> struct C -> struct A
824/// @endcode
825std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
826 std::string PathDisplayStr;
827 std::set<unsigned> DisplayedPaths;
828 for (CXXBasePaths::paths_iterator Path = Paths.begin();
829 Path != Paths.end(); ++Path) {
830 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
831 // We haven't displayed a path to this particular base
832 // class subobject yet.
833 PathDisplayStr += "\n ";
834 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
835 for (CXXBasePath::const_iterator Element = Path->begin();
836 Element != Path->end(); ++Element)
837 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
838 }
839 }
840
841 return PathDisplayStr;
842}
843
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000844//===----------------------------------------------------------------------===//
845// C++ class member Handling
846//===----------------------------------------------------------------------===//
847
Abramo Bagnara6206d532010-06-05 05:09:32 +0000848/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000849Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
850 SourceLocation ASLoc,
851 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000852 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000853 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000854 ASLoc, ColonLoc);
855 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000856 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000857}
858
Anders Carlsson9e682d92011-01-20 05:57:14 +0000859/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000860void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000861 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
862 if (!MD || !MD->isVirtual())
863 return;
864
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000865 if (MD->isDependentContext())
866 return;
867
Anders Carlsson9e682d92011-01-20 05:57:14 +0000868 // C++0x [class.virtual]p3:
869 // If a virtual function is marked with the virt-specifier override and does
870 // not override a member function of a base class,
871 // the program is ill-formed.
872 bool HasOverriddenMethods =
873 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000874 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000875 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000876 diag::err_function_marked_override_not_overriding)
877 << MD->getDeclName();
878 return;
879 }
Anders Carlssonaa23d282011-01-22 22:23:37 +0000880
881 // C++0x [class.derived]p8:
882 // In a class definition marked with the class-virt-specifier explicit,
883 // if a virtual member function that is neither implicitly-declared nor a
884 // destructor overrides a member function of a base class and it is not
885 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000886 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
887 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlssonaa23d282011-01-22 22:23:37 +0000888 llvm::SmallVector<const CXXMethodDecl*, 4>
889 OverriddenMethods(MD->begin_overridden_methods(),
890 MD->end_overridden_methods());
891
892 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
893 << MD->getDeclName()
894 << (unsigned)OverriddenMethods.size();
895
896 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
897 Diag(OverriddenMethods[I]->getLocation(),
898 diag::note_overridden_virtual_function);
899 }
Anders Carlsson9e682d92011-01-20 05:57:14 +0000900}
901
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000902/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
903/// function overrides a virtual member function marked 'final', according to
904/// C++0x [class.virtual]p3.
905bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
906 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000907 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000908 return false;
909
910 Diag(New->getLocation(), diag::err_final_function_overridden)
911 << New->getDeclName();
912 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
913 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000914}
915
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000916/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
917/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
918/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000919/// any.
John McCalld226f652010-08-21 09:40:31 +0000920Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000922 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000923 ExprTy *BW, const VirtSpecifiers &VS,
924 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000925 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000926 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000927 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
928 DeclarationName Name = NameInfo.getName();
929 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000930
931 // For anonymous bitfields, the location should point to the type.
932 if (Loc.isInvalid())
933 Loc = D.getSourceRange().getBegin();
934
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000935 Expr *BitWidth = static_cast<Expr*>(BW);
936 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000937
John McCall4bde1e12010-06-04 08:34:12 +0000938 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000939 assert(!DS.isFriendSpecified());
940
John McCall4bde1e12010-06-04 08:34:12 +0000941 bool isFunc = false;
942 if (D.isFunctionDeclarator())
943 isFunc = true;
944 else if (D.getNumTypeObjects() == 0 &&
945 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000946 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000947 isFunc = TDType->isFunctionType();
948 }
949
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000950 // C++ 9.2p6: A member shall not be declared to have automatic storage
951 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000952 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
953 // data members and cannot be applied to names declared const or static,
954 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000955 switch (DS.getStorageClassSpec()) {
956 case DeclSpec::SCS_unspecified:
957 case DeclSpec::SCS_typedef:
958 case DeclSpec::SCS_static:
959 // FALL THROUGH.
960 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000961 case DeclSpec::SCS_mutable:
962 if (isFunc) {
963 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000964 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000965 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000966 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Sebastian Redla11f42f2008-11-17 23:24:37 +0000968 // FIXME: It would be nicer if the keyword was ignored only for this
969 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000970 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000971 }
972 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000973 default:
974 if (DS.getStorageClassSpecLoc().isValid())
975 Diag(DS.getStorageClassSpecLoc(),
976 diag::err_storageclass_invalid_for_member);
977 else
978 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
979 D.getMutableDeclSpec().ClearStorageClassSpecs();
980 }
981
Sebastian Redl669d5d72008-11-14 23:42:31 +0000982 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
983 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000984 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000985
986 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000987 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000988 CXXScopeSpec &SS = D.getCXXScopeSpec();
989
990
991 if (SS.isSet() && !SS.isInvalid()) {
992 // The user provided a superfluous scope specifier inside a class
993 // definition:
994 //
995 // class X {
996 // int X::member;
997 // };
998 DeclContext *DC = 0;
999 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1000 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1001 << Name << FixItHint::CreateRemoval(SS.getRange());
1002 else
1003 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1004 << Name << SS.getRange();
1005
1006 SS.clear();
1007 }
1008
Douglas Gregor37b372b2009-08-20 22:52:58 +00001009 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001010 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001011 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1012 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001013 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001014 } else {
John McCalld226f652010-08-21 09:40:31 +00001015 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001016 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001017 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001018 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001019
1020 // Non-instance-fields can't have a bitfield.
1021 if (BitWidth) {
1022 if (Member->isInvalidDecl()) {
1023 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001024 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001025 // C++ 9.6p3: A bit-field shall not be a static member.
1026 // "static member 'A' cannot be a bit-field"
1027 Diag(Loc, diag::err_static_not_bitfield)
1028 << Name << BitWidth->getSourceRange();
1029 } else if (isa<TypedefDecl>(Member)) {
1030 // "typedef member 'x' cannot be a bit-field"
1031 Diag(Loc, diag::err_typedef_not_bitfield)
1032 << Name << BitWidth->getSourceRange();
1033 } else {
1034 // A function typedef ("typedef int f(); f a;").
1035 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1036 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001037 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001038 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chris Lattner8b963ef2009-03-05 23:01:03 +00001041 BitWidth = 0;
1042 Member->setInvalidDecl();
1043 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001044
1045 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Douglas Gregor37b372b2009-08-20 22:52:58 +00001047 // If we have declared a member function template, set the access of the
1048 // templated declaration as well.
1049 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1050 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001051 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001052
Anders Carlssonaae5af22011-01-20 04:34:22 +00001053 if (VS.isOverrideSpecified()) {
1054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1055 if (!MD || !MD->isVirtual()) {
1056 Diag(Member->getLocStart(),
1057 diag::override_keyword_only_allowed_on_virtual_member_functions)
1058 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001059 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001060 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001061 }
1062 if (VS.isFinalSpecified()) {
1063 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1064 if (!MD || !MD->isVirtual()) {
1065 Diag(Member->getLocStart(),
1066 diag::override_keyword_only_allowed_on_virtual_member_functions)
1067 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001068 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001069 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001070 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001071
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001072 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001073
Douglas Gregor10bd3682008-11-17 22:58:34 +00001074 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075
Douglas Gregor021c3b32009-03-11 23:00:04 +00001076 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001077 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001078 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001079 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001080
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001081 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001082 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001083 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 }
John McCalld226f652010-08-21 09:40:31 +00001085 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001086}
1087
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001088/// \brief Find the direct and/or virtual base specifiers that
1089/// correspond to the given base type, for use in base initialization
1090/// within a constructor.
1091static bool FindBaseInitializer(Sema &SemaRef,
1092 CXXRecordDecl *ClassDecl,
1093 QualType BaseType,
1094 const CXXBaseSpecifier *&DirectBaseSpec,
1095 const CXXBaseSpecifier *&VirtualBaseSpec) {
1096 // First, check for a direct base class.
1097 DirectBaseSpec = 0;
1098 for (CXXRecordDecl::base_class_const_iterator Base
1099 = ClassDecl->bases_begin();
1100 Base != ClassDecl->bases_end(); ++Base) {
1101 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1102 // We found a direct base of this type. That's what we're
1103 // initializing.
1104 DirectBaseSpec = &*Base;
1105 break;
1106 }
1107 }
1108
1109 // Check for a virtual base class.
1110 // FIXME: We might be able to short-circuit this if we know in advance that
1111 // there are no virtual bases.
1112 VirtualBaseSpec = 0;
1113 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1114 // We haven't found a base yet; search the class hierarchy for a
1115 // virtual base class.
1116 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1117 /*DetectVirtual=*/false);
1118 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1119 BaseType, Paths)) {
1120 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1121 Path != Paths.end(); ++Path) {
1122 if (Path->back().Base->isVirtual()) {
1123 VirtualBaseSpec = Path->back().Base;
1124 break;
1125 }
1126 }
1127 }
1128 }
1129
1130 return DirectBaseSpec || VirtualBaseSpec;
1131}
1132
Douglas Gregor7ad83902008-11-05 04:29:56 +00001133/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001134MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001135Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001136 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001137 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001138 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001139 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001140 SourceLocation IdLoc,
1141 SourceLocation LParenLoc,
1142 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001143 SourceLocation RParenLoc,
1144 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001145 if (!ConstructorD)
1146 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001148 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
1150 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001151 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001152 if (!Constructor) {
1153 // The user wrote a constructor initializer on a function that is
1154 // not a C++ constructor. Ignore the error for now, because we may
1155 // have more member initializers coming; we'll diagnose it just
1156 // once in ActOnMemInitializers.
1157 return true;
1158 }
1159
1160 CXXRecordDecl *ClassDecl = Constructor->getParent();
1161
1162 // C++ [class.base.init]p2:
1163 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001164 // constructor's class and, if not found in that scope, are looked
1165 // up in the scope containing the constructor's definition.
1166 // [Note: if the constructor's class contains a member with the
1167 // same name as a direct or virtual base class of the class, a
1168 // mem-initializer-id naming the member or base class and composed
1169 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001170 // mem-initializer-id for the hidden base class may be specified
1171 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001172 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001173 // Look for a member, first.
1174 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001175 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001176 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001177 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001178 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001179
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001180 if (Member) {
1181 if (EllipsisLoc.isValid())
1182 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1183 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1184
Francois Pichet00eb3f92010-12-04 09:14:42 +00001185 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001186 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001187 }
1188
Francois Pichet00eb3f92010-12-04 09:14:42 +00001189 // Handle anonymous union case.
1190 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001191 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1192 if (EllipsisLoc.isValid())
1193 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1194 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1195
Francois Pichet00eb3f92010-12-04 09:14:42 +00001196 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1197 NumArgs, IdLoc,
1198 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001199 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001200 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001201 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001202 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001203 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001204 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001205
1206 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001207 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001208 } else {
1209 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1210 LookupParsedName(R, S, &SS);
1211
1212 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1213 if (!TyD) {
1214 if (R.isAmbiguous()) return true;
1215
John McCallfd225442010-04-09 19:01:14 +00001216 // We don't want access-control diagnostics here.
1217 R.suppressDiagnostics();
1218
Douglas Gregor7a886e12010-01-19 06:46:48 +00001219 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1220 bool NotUnknownSpecialization = false;
1221 DeclContext *DC = computeDeclContext(SS, false);
1222 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1223 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1224
1225 if (!NotUnknownSpecialization) {
1226 // When the scope specifier can refer to a member of an unknown
1227 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001228 BaseType = CheckTypenameType(ETK_None,
1229 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001230 *MemberOrBase, SourceLocation(),
1231 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001232 if (BaseType.isNull())
1233 return true;
1234
Douglas Gregor7a886e12010-01-19 06:46:48 +00001235 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001236 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001237 }
1238 }
1239
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001240 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001241 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001242 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1243 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001244 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001245 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001246 // We have found a non-static data member with a similar
1247 // name to what was typed; complain and initialize that
1248 // member.
1249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1250 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001251 << FixItHint::CreateReplacement(R.getNameLoc(),
1252 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001253 Diag(Member->getLocation(), diag::note_previous_decl)
1254 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001255
1256 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1257 LParenLoc, RParenLoc);
1258 }
1259 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1260 const CXXBaseSpecifier *DirectBaseSpec;
1261 const CXXBaseSpecifier *VirtualBaseSpec;
1262 if (FindBaseInitializer(*this, ClassDecl,
1263 Context.getTypeDeclType(Type),
1264 DirectBaseSpec, VirtualBaseSpec)) {
1265 // We have found a direct or virtual base class with a
1266 // similar name to what was typed; complain and initialize
1267 // that base class.
1268 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1269 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001270 << FixItHint::CreateReplacement(R.getNameLoc(),
1271 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001272
1273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1274 : VirtualBaseSpec;
1275 Diag(BaseSpec->getSourceRange().getBegin(),
1276 diag::note_base_class_specified_here)
1277 << BaseSpec->getType()
1278 << BaseSpec->getSourceRange();
1279
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001280 TyD = Type;
1281 }
1282 }
1283 }
1284
Douglas Gregor7a886e12010-01-19 06:46:48 +00001285 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001286 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1287 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1288 return true;
1289 }
John McCall2b194412009-12-21 10:41:20 +00001290 }
1291
Douglas Gregor7a886e12010-01-19 06:46:48 +00001292 if (BaseType.isNull()) {
1293 BaseType = Context.getTypeDeclType(TyD);
1294 if (SS.isSet()) {
1295 NestedNameSpecifier *Qualifier =
1296 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001297
Douglas Gregor7a886e12010-01-19 06:46:48 +00001298 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001299 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001300 }
John McCall2b194412009-12-21 10:41:20 +00001301 }
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCalla93c9342009-12-07 02:54:59 +00001304 if (!TInfo)
1305 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001306
John McCalla93c9342009-12-07 02:54:59 +00001307 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001308 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001309}
1310
John McCallb4190042009-11-04 23:02:40 +00001311/// Checks an initializer expression for use of uninitialized fields, such as
1312/// containing the field that is being initialized. Returns true if there is an
1313/// uninitialized field was used an updates the SourceLocation parameter; false
1314/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001315static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001316 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001317 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001318 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1319
Nick Lewycky43ad1822010-06-15 07:32:55 +00001320 if (isa<CallExpr>(S)) {
1321 // Do not descend into function calls or constructors, as the use
1322 // of an uninitialized field may be valid. One would have to inspect
1323 // the contents of the function/ctor to determine if it is safe or not.
1324 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1325 // may be safe, depending on what the function/ctor does.
1326 return false;
1327 }
1328 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1329 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001330
1331 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1332 // The member expression points to a static data member.
1333 assert(VD->isStaticDataMember() &&
1334 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001335 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001336 return false;
1337 }
1338
1339 if (isa<EnumConstantDecl>(RhsField)) {
1340 // The member expression points to an enum.
1341 return false;
1342 }
1343
John McCallb4190042009-11-04 23:02:40 +00001344 if (RhsField == LhsField) {
1345 // Initializing a field with itself. Throw a warning.
1346 // But wait; there are exceptions!
1347 // Exception #1: The field may not belong to this record.
1348 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001349 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001350 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1351 // Even though the field matches, it does not belong to this record.
1352 return false;
1353 }
1354 // None of the exceptions triggered; return true to indicate an
1355 // uninitialized field was used.
1356 *L = ME->getMemberLoc();
1357 return true;
1358 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001359 } else if (isa<SizeOfAlignOfExpr>(S)) {
1360 // sizeof/alignof doesn't reference contents, do not warn.
1361 return false;
1362 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1363 // address-of doesn't reference contents (the pointer may be dereferenced
1364 // in the same expression but it would be rare; and weird).
1365 if (UOE->getOpcode() == UO_AddrOf)
1366 return false;
John McCallb4190042009-11-04 23:02:40 +00001367 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001368 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1369 it != e; ++it) {
1370 if (!*it) {
1371 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001372 continue;
1373 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001374 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1375 return true;
John McCallb4190042009-11-04 23:02:40 +00001376 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001377 return false;
John McCallb4190042009-11-04 23:02:40 +00001378}
1379
John McCallf312b1e2010-08-26 23:41:50 +00001380MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001381Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001382 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001383 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001384 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001385 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1386 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1387 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001388 "Member must be a FieldDecl or IndirectFieldDecl");
1389
Douglas Gregor464b2f02010-11-05 22:21:31 +00001390 if (Member->isInvalidDecl())
1391 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001392
John McCallb4190042009-11-04 23:02:40 +00001393 // Diagnose value-uses of fields to initialize themselves, e.g.
1394 // foo(foo)
1395 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001396 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001397 for (unsigned i = 0; i < NumArgs; ++i) {
1398 SourceLocation L;
1399 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1400 // FIXME: Return true in the case when other fields are used before being
1401 // uninitialized. For example, let this field be the i'th field. When
1402 // initializing the i'th field, throw a warning if any of the >= i'th
1403 // fields are used, as they are not yet initialized.
1404 // Right now we are only handling the case where the i'th field uses
1405 // itself in its initializer.
1406 Diag(L, diag::warn_field_is_uninit);
1407 }
1408 }
1409
Eli Friedman59c04372009-07-29 19:44:27 +00001410 bool HasDependentArg = false;
1411 for (unsigned i = 0; i < NumArgs; i++)
1412 HasDependentArg |= Args[i]->isTypeDependent();
1413
Chandler Carruth894aed92010-12-06 09:23:57 +00001414 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001415 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416 // Can't check initialization for a member of dependent type or when
1417 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001418 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1419 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001420
1421 // Erase any temporaries within this evaluation context; we're not
1422 // going to track them in the AST, since we'll be rebuilding the
1423 // ASTs during template instantiation.
1424 ExprTemporaries.erase(
1425 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1426 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001427 } else {
1428 // Initialize the member.
1429 InitializedEntity MemberEntity =
1430 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1431 : InitializedEntity::InitializeMember(IndirectMember, 0);
1432 InitializationKind Kind =
1433 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001434
Chandler Carruth894aed92010-12-06 09:23:57 +00001435 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1436
1437 ExprResult MemberInit =
1438 InitSeq.Perform(*this, MemberEntity, Kind,
1439 MultiExprArg(*this, Args, NumArgs), 0);
1440 if (MemberInit.isInvalid())
1441 return true;
1442
1443 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1444
1445 // C++0x [class.base.init]p7:
1446 // The initialization of each base and member constitutes a
1447 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001448 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001449 if (MemberInit.isInvalid())
1450 return true;
1451
1452 // If we are in a dependent context, template instantiation will
1453 // perform this type-checking again. Just save the arguments that we
1454 // received in a ParenListExpr.
1455 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1456 // of the information that we have about the member
1457 // initializer. However, deconstructing the ASTs is a dicey process,
1458 // and this approach is far more likely to get the corner cases right.
1459 if (CurContext->isDependentContext())
1460 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1461 RParenLoc);
1462 else
1463 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001464 }
1465
Chandler Carruth894aed92010-12-06 09:23:57 +00001466 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001467 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001468 IdLoc, LParenLoc, Init,
1469 RParenLoc);
1470 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001471 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001472 IdLoc, LParenLoc, Init,
1473 RParenLoc);
1474 }
Eli Friedman59c04372009-07-29 19:44:27 +00001475}
1476
John McCallf312b1e2010-08-26 23:41:50 +00001477MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001478Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1479 Expr **Args, unsigned NumArgs,
1480 SourceLocation LParenLoc,
1481 SourceLocation RParenLoc,
1482 CXXRecordDecl *ClassDecl,
1483 SourceLocation EllipsisLoc) {
1484 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1485 if (!LangOpts.CPlusPlus0x)
1486 return Diag(Loc, diag::err_delegation_0x_only)
1487 << TInfo->getTypeLoc().getLocalSourceRange();
1488
1489 return Diag(Loc, diag::err_delegation_unimplemented)
1490 << TInfo->getTypeLoc().getLocalSourceRange();
1491}
1492
1493MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001494Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001495 Expr **Args, unsigned NumArgs,
1496 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001497 CXXRecordDecl *ClassDecl,
1498 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001499 bool HasDependentArg = false;
1500 for (unsigned i = 0; i < NumArgs; i++)
1501 HasDependentArg |= Args[i]->isTypeDependent();
1502
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001503 SourceLocation BaseLoc
1504 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1505
1506 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1507 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1508 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1509
1510 // C++ [class.base.init]p2:
1511 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001512 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001513 // of that class, the mem-initializer is ill-formed. A
1514 // mem-initializer-list can initialize a base class using any
1515 // name that denotes that base class type.
1516 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1517
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001518 if (EllipsisLoc.isValid()) {
1519 // This is a pack expansion.
1520 if (!BaseType->containsUnexpandedParameterPack()) {
1521 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1522 << SourceRange(BaseLoc, RParenLoc);
1523
1524 EllipsisLoc = SourceLocation();
1525 }
1526 } else {
1527 // Check for any unexpanded parameter packs.
1528 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1529 return true;
1530
1531 for (unsigned I = 0; I != NumArgs; ++I)
1532 if (DiagnoseUnexpandedParameterPack(Args[I]))
1533 return true;
1534 }
1535
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001536 // Check for direct and virtual base classes.
1537 const CXXBaseSpecifier *DirectBaseSpec = 0;
1538 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1539 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001540 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1541 BaseType))
1542 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1543 LParenLoc, RParenLoc, ClassDecl,
1544 EllipsisLoc);
1545
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001546 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1547 VirtualBaseSpec);
1548
1549 // C++ [base.class.init]p2:
1550 // Unless the mem-initializer-id names a nonstatic data member of the
1551 // constructor's class or a direct or virtual base of that class, the
1552 // mem-initializer is ill-formed.
1553 if (!DirectBaseSpec && !VirtualBaseSpec) {
1554 // If the class has any dependent bases, then it's possible that
1555 // one of those types will resolve to the same type as
1556 // BaseType. Therefore, just treat this as a dependent base
1557 // class initialization. FIXME: Should we try to check the
1558 // initialization anyway? It seems odd.
1559 if (ClassDecl->hasAnyDependentBases())
1560 Dependent = true;
1561 else
1562 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1563 << BaseType << Context.getTypeDeclType(ClassDecl)
1564 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1565 }
1566 }
1567
1568 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001569 // Can't check initialization for a base of dependent type or when
1570 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001571 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001572 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1573 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001574
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001575 // Erase any temporaries within this evaluation context; we're not
1576 // going to track them in the AST, since we'll be rebuilding the
1577 // ASTs during template instantiation.
1578 ExprTemporaries.erase(
1579 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1580 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Sean Huntcbb67482011-01-08 20:30:50 +00001582 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001583 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001584 LParenLoc,
1585 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001586 RParenLoc,
1587 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001588 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001589
1590 // C++ [base.class.init]p2:
1591 // If a mem-initializer-id is ambiguous because it designates both
1592 // a direct non-virtual base class and an inherited virtual base
1593 // class, the mem-initializer is ill-formed.
1594 if (DirectBaseSpec && VirtualBaseSpec)
1595 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001596 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001597
1598 CXXBaseSpecifier *BaseSpec
1599 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1600 if (!BaseSpec)
1601 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1602
1603 // Initialize the base.
1604 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001605 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001606 InitializationKind Kind =
1607 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1608
1609 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1610
John McCall60d7b3a2010-08-24 06:29:42 +00001611 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001612 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001613 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001614 if (BaseInit.isInvalid())
1615 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001616
1617 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001618
1619 // C++0x [class.base.init]p7:
1620 // The initialization of each base and member constitutes a
1621 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001622 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001623 if (BaseInit.isInvalid())
1624 return true;
1625
1626 // If we are in a dependent context, template instantiation will
1627 // perform this type-checking again. Just save the arguments that we
1628 // received in a ParenListExpr.
1629 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1630 // of the information that we have about the base
1631 // initializer. However, deconstructing the ASTs is a dicey process,
1632 // and this approach is far more likely to get the corner cases right.
1633 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001634 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001635 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1636 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001638 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001639 LParenLoc,
1640 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001641 RParenLoc,
1642 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001643 }
1644
Sean Huntcbb67482011-01-08 20:30:50 +00001645 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001646 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001647 LParenLoc,
1648 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001649 RParenLoc,
1650 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001651}
1652
Anders Carlssone5ef7402010-04-23 03:10:23 +00001653/// ImplicitInitializerKind - How an implicit base or member initializer should
1654/// initialize its base or member.
1655enum ImplicitInitializerKind {
1656 IIK_Default,
1657 IIK_Copy,
1658 IIK_Move
1659};
1660
Anders Carlssondefefd22010-04-23 02:00:02 +00001661static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001662BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001663 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001664 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001665 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001666 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001667 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001668 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1669 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001670
John McCall60d7b3a2010-08-24 06:29:42 +00001671 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001672
1673 switch (ImplicitInitKind) {
1674 case IIK_Default: {
1675 InitializationKind InitKind
1676 = InitializationKind::CreateDefault(Constructor->getLocation());
1677 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1678 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001679 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001680 break;
1681 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001682
Anders Carlssone5ef7402010-04-23 03:10:23 +00001683 case IIK_Copy: {
1684 ParmVarDecl *Param = Constructor->getParamDecl(0);
1685 QualType ParamType = Param->getType().getNonReferenceType();
1686
1687 Expr *CopyCtorArg =
1688 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001689 Constructor->getLocation(), ParamType,
1690 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001691
Anders Carlssonc7957502010-04-24 22:02:54 +00001692 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001693 QualType ArgTy =
1694 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1695 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001696
1697 CXXCastPath BasePath;
1698 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001699 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001700 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001701 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001702
Anders Carlssone5ef7402010-04-23 03:10:23 +00001703 InitializationKind InitKind
1704 = InitializationKind::CreateDirect(Constructor->getLocation(),
1705 SourceLocation(), SourceLocation());
1706 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1707 &CopyCtorArg, 1);
1708 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001709 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001710 break;
1711 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001712
Anders Carlssone5ef7402010-04-23 03:10:23 +00001713 case IIK_Move:
1714 assert(false && "Unhandled initializer kind!");
1715 }
John McCall9ae2f072010-08-23 23:25:46 +00001716
Douglas Gregor53c374f2010-12-07 00:41:46 +00001717 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001718 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001719 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001720
Anders Carlssondefefd22010-04-23 02:00:02 +00001721 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001722 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001723 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1724 SourceLocation()),
1725 BaseSpec->isVirtual(),
1726 SourceLocation(),
1727 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001728 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001729 SourceLocation());
1730
Anders Carlssondefefd22010-04-23 02:00:02 +00001731 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001732}
1733
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001734static bool
1735BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001736 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001737 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001738 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001739 if (Field->isInvalidDecl())
1740 return true;
1741
Chandler Carruthf186b542010-06-29 23:50:44 +00001742 SourceLocation Loc = Constructor->getLocation();
1743
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001744 if (ImplicitInitKind == IIK_Copy) {
1745 ParmVarDecl *Param = Constructor->getParamDecl(0);
1746 QualType ParamType = Param->getType().getNonReferenceType();
1747
1748 Expr *MemberExprBase =
1749 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001750 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001751
1752 // Build a reference to this field within the parameter.
1753 CXXScopeSpec SS;
1754 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1755 Sema::LookupMemberName);
1756 MemberLookup.addDecl(Field, AS_public);
1757 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001758 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001760 ParamType, Loc,
1761 /*IsArrow=*/false,
1762 SS,
1763 /*FirstQualifierInScope=*/0,
1764 MemberLookup,
1765 /*TemplateArgs=*/0);
1766 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001767 return true;
1768
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001769 // When the field we are copying is an array, create index variables for
1770 // each dimension of the array. We use these index variables to subscript
1771 // the source array, and other clients (e.g., CodeGen) will perform the
1772 // necessary iteration with these index variables.
1773 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1774 QualType BaseType = Field->getType();
1775 QualType SizeType = SemaRef.Context.getSizeType();
1776 while (const ConstantArrayType *Array
1777 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1778 // Create the iteration variable for this array index.
1779 IdentifierInfo *IterationVarName = 0;
1780 {
1781 llvm::SmallString<8> Str;
1782 llvm::raw_svector_ostream OS(Str);
1783 OS << "__i" << IndexVariables.size();
1784 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1785 }
1786 VarDecl *IterationVar
1787 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1788 IterationVarName, SizeType,
1789 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001790 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001791 IndexVariables.push_back(IterationVar);
1792
1793 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001794 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001795 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001796 assert(!IterationVarRef.isInvalid() &&
1797 "Reference to invented variable cannot fail!");
1798
1799 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001800 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001801 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001802 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001803 Loc);
1804 if (CopyCtorArg.isInvalid())
1805 return true;
1806
1807 BaseType = Array->getElementType();
1808 }
1809
1810 // Construct the entity that we will be initializing. For an array, this
1811 // will be first element in the array, which may require several levels
1812 // of array-subscript entities.
1813 llvm::SmallVector<InitializedEntity, 4> Entities;
1814 Entities.reserve(1 + IndexVariables.size());
1815 Entities.push_back(InitializedEntity::InitializeMember(Field));
1816 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1817 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1818 0,
1819 Entities.back()));
1820
1821 // Direct-initialize to use the copy constructor.
1822 InitializationKind InitKind =
1823 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1824
1825 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1826 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1827 &CopyCtorArgE, 1);
1828
John McCall60d7b3a2010-08-24 06:29:42 +00001829 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001830 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001831 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001832 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001833 if (MemberInit.isInvalid())
1834 return true;
1835
1836 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001837 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001838 MemberInit.takeAs<Expr>(), Loc,
1839 IndexVariables.data(),
1840 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001841 return false;
1842 }
1843
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001844 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1845
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001846 QualType FieldBaseElementType =
1847 SemaRef.Context.getBaseElementType(Field->getType());
1848
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001849 if (FieldBaseElementType->isRecordType()) {
1850 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001851 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001852 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001853
1854 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001855 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001856 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001857
Douglas Gregor53c374f2010-12-07 00:41:46 +00001858 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001859 if (MemberInit.isInvalid())
1860 return true;
1861
1862 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001863 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001864 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001865 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001866 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001867 return false;
1868 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001869
1870 if (FieldBaseElementType->isReferenceType()) {
1871 SemaRef.Diag(Constructor->getLocation(),
1872 diag::err_uninitialized_member_in_ctor)
1873 << (int)Constructor->isImplicit()
1874 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1875 << 0 << Field->getDeclName();
1876 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1877 return true;
1878 }
1879
1880 if (FieldBaseElementType.isConstQualified()) {
1881 SemaRef.Diag(Constructor->getLocation(),
1882 diag::err_uninitialized_member_in_ctor)
1883 << (int)Constructor->isImplicit()
1884 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1885 << 1 << Field->getDeclName();
1886 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1887 return true;
1888 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001889
1890 // Nothing to initialize.
1891 CXXMemberInit = 0;
1892 return false;
1893}
John McCallf1860e52010-05-20 23:23:51 +00001894
1895namespace {
1896struct BaseAndFieldInfo {
1897 Sema &S;
1898 CXXConstructorDecl *Ctor;
1899 bool AnyErrorsInInits;
1900 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001901 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1902 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001903
1904 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1905 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1906 // FIXME: Handle implicit move constructors.
1907 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1908 IIK = IIK_Copy;
1909 else
1910 IIK = IIK_Default;
1911 }
1912};
1913}
1914
1915static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1916 FieldDecl *Top, FieldDecl *Field) {
1917
Chandler Carruthe861c602010-06-30 02:59:29 +00001918 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00001919 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001920 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001921 return false;
1922 }
1923
1924 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1925 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1926 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001927 CXXRecordDecl *FieldClassDecl
1928 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001929
1930 // Even though union members never have non-trivial default
1931 // constructions in C++03, we still build member initializers for aggregate
1932 // record types which can be union members, and C++0x allows non-trivial
1933 // default constructors for union members, so we ensure that only one
1934 // member is initialized for these.
1935 if (FieldClassDecl->isUnion()) {
1936 // First check for an explicit initializer for one field.
1937 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1938 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00001939 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001940 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001941
1942 // Once we've initialized a field of an anonymous union, the union
1943 // field in the class is also initialized, so exit immediately.
1944 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001945 } else if ((*FA)->isAnonymousStructOrUnion()) {
1946 if (CollectFieldInitializer(Info, Top, *FA))
1947 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001948 }
1949 }
1950
1951 // Fallthrough and construct a default initializer for the union as
1952 // a whole, which can call its default constructor if such a thing exists
1953 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1954 // behavior going forward with C++0x, when anonymous unions there are
1955 // finalized, we should revisit this.
1956 } else {
1957 // For structs, we simply descend through to initialize all members where
1958 // necessary.
1959 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1960 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1961 if (CollectFieldInitializer(Info, Top, *FA))
1962 return true;
1963 }
1964 }
John McCallf1860e52010-05-20 23:23:51 +00001965 }
1966
1967 // Don't try to build an implicit initializer if there were semantic
1968 // errors in any of the initializers (and therefore we might be
1969 // missing some that the user actually wrote).
1970 if (Info.AnyErrorsInInits)
1971 return false;
1972
Sean Huntcbb67482011-01-08 20:30:50 +00001973 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00001974 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1975 return true;
John McCallf1860e52010-05-20 23:23:51 +00001976
Francois Pichet00eb3f92010-12-04 09:14:42 +00001977 if (Init)
1978 Info.AllToInit.push_back(Init);
1979
John McCallf1860e52010-05-20 23:23:51 +00001980 return false;
1981}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001982
Eli Friedman80c30da2009-11-09 19:20:36 +00001983bool
Sean Huntcbb67482011-01-08 20:30:50 +00001984Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1985 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001986 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001987 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001988 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001989 // Just store the initializers as written, they will be checked during
1990 // instantiation.
1991 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00001992 Constructor->setNumCtorInitializers(NumInitializers);
1993 CXXCtorInitializer **baseOrMemberInitializers =
1994 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001995 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00001996 NumInitializers * sizeof(CXXCtorInitializer*));
1997 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001998 }
1999
2000 return false;
2001 }
2002
John McCallf1860e52010-05-20 23:23:51 +00002003 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002004
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002005 // We need to build the initializer AST according to order of construction
2006 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002007 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002008 if (!ClassDecl)
2009 return true;
2010
Eli Friedman80c30da2009-11-09 19:20:36 +00002011 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002013 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002014 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002015
2016 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002017 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002018 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002019 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002020 }
2021
Anders Carlsson711f34a2010-04-21 19:52:01 +00002022 // Keep track of the direct virtual bases.
2023 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2024 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2025 E = ClassDecl->bases_end(); I != E; ++I) {
2026 if (I->isVirtual())
2027 DirectVBases.insert(I);
2028 }
2029
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002030 // Push virtual bases before others.
2031 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2032 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2033
Sean Huntcbb67482011-01-08 20:30:50 +00002034 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002035 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2036 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002037 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002038 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002039 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002040 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002041 VBase, IsInheritedVirtualBase,
2042 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002043 HadError = true;
2044 continue;
2045 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002046
John McCallf1860e52010-05-20 23:23:51 +00002047 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002048 }
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
John McCallf1860e52010-05-20 23:23:51 +00002051 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2053 E = ClassDecl->bases_end(); Base != E; ++Base) {
2054 // Virtuals are in the virtual base list and already constructed.
2055 if (Base->isVirtual())
2056 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Sean Huntcbb67482011-01-08 20:30:50 +00002058 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002059 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2060 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002061 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002062 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002063 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002064 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002065 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002066 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002067 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002068 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002069
John McCallf1860e52010-05-20 23:23:51 +00002070 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002071 }
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
John McCallf1860e52010-05-20 23:23:51 +00002074 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002075 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002076 E = ClassDecl->field_end(); Field != E; ++Field) {
2077 if ((*Field)->getType()->isIncompleteArrayType()) {
2078 assert(ClassDecl->hasFlexibleArrayMember() &&
2079 "Incomplete array type is not valid");
2080 continue;
2081 }
John McCallf1860e52010-05-20 23:23:51 +00002082 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002083 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
John McCallf1860e52010-05-20 23:23:51 +00002086 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002087 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002088 Constructor->setNumCtorInitializers(NumInitializers);
2089 CXXCtorInitializer **baseOrMemberInitializers =
2090 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002091 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002092 NumInitializers * sizeof(CXXCtorInitializer*));
2093 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002094
John McCallef027fe2010-03-16 21:39:52 +00002095 // Constructors implicitly reference the base and member
2096 // destructors.
2097 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2098 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002099 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002100
2101 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002102}
2103
Eli Friedman6347f422009-07-21 19:28:10 +00002104static void *GetKeyForTopLevelField(FieldDecl *Field) {
2105 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002106 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002107 if (RT->getDecl()->isAnonymousStructOrUnion())
2108 return static_cast<void *>(RT->getDecl());
2109 }
2110 return static_cast<void *>(Field);
2111}
2112
Anders Carlssonea356fb2010-04-02 05:42:15 +00002113static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002114 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002115}
2116
Anders Carlssonea356fb2010-04-02 05:42:15 +00002117static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002118 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002119 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002120 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002121
Eli Friedman6347f422009-07-21 19:28:10 +00002122 // For fields injected into the class via declaration of an anonymous union,
2123 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002124 FieldDecl *Field = Member->getAnyMember();
2125
John McCall3c3ccdb2010-04-10 09:28:51 +00002126 // If the field is a member of an anonymous struct or union, our key
2127 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002128 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002129 if (RD->isAnonymousStructOrUnion()) {
2130 while (true) {
2131 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2132 if (Parent->isAnonymousStructOrUnion())
2133 RD = Parent;
2134 else
2135 break;
2136 }
2137
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002138 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002141 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002142}
2143
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002144static void
2145DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002146 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002147 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002148 unsigned NumInits) {
2149 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002150 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002152 // Don't check initializers order unless the warning is enabled at the
2153 // location of at least one initializer.
2154 bool ShouldCheckOrder = false;
2155 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002156 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002157 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2158 Init->getSourceLocation())
2159 != Diagnostic::Ignored) {
2160 ShouldCheckOrder = true;
2161 break;
2162 }
2163 }
2164 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002165 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002166
John McCalld6ca8da2010-04-10 07:37:23 +00002167 // Build the list of bases and members in the order that they'll
2168 // actually be initialized. The explicit initializers should be in
2169 // this same order but may be missing things.
2170 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Anders Carlsson071d6102010-04-02 03:38:04 +00002172 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2173
John McCalld6ca8da2010-04-10 07:37:23 +00002174 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002175 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002176 ClassDecl->vbases_begin(),
2177 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002178 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002179
John McCalld6ca8da2010-04-10 07:37:23 +00002180 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002181 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002182 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002183 if (Base->isVirtual())
2184 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002185 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002186 }
Mike Stump1eb44332009-09-09 15:08:12 +00002187
John McCalld6ca8da2010-04-10 07:37:23 +00002188 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002189 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2190 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002191 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002192
John McCalld6ca8da2010-04-10 07:37:23 +00002193 unsigned NumIdealInits = IdealInitKeys.size();
2194 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002195
Sean Huntcbb67482011-01-08 20:30:50 +00002196 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002197 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002198 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002199 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002200
2201 // Scan forward to try to find this initializer in the idealized
2202 // initializers list.
2203 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2204 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002205 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002206
2207 // If we didn't find this initializer, it must be because we
2208 // scanned past it on a previous iteration. That can only
2209 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002210 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002211 Sema::SemaDiagnosticBuilder D =
2212 SemaRef.Diag(PrevInit->getSourceLocation(),
2213 diag::warn_initializer_out_of_order);
2214
Francois Pichet00eb3f92010-12-04 09:14:42 +00002215 if (PrevInit->isAnyMemberInitializer())
2216 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002217 else
2218 D << 1 << PrevInit->getBaseClassInfo()->getType();
2219
Francois Pichet00eb3f92010-12-04 09:14:42 +00002220 if (Init->isAnyMemberInitializer())
2221 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002222 else
2223 D << 1 << Init->getBaseClassInfo()->getType();
2224
2225 // Move back to the initializer's location in the ideal list.
2226 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2227 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002228 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002229
2230 assert(IdealIndex != NumIdealInits &&
2231 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002232 }
John McCalld6ca8da2010-04-10 07:37:23 +00002233
2234 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002235 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002236}
2237
John McCall3c3ccdb2010-04-10 09:28:51 +00002238namespace {
2239bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002240 CXXCtorInitializer *Init,
2241 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002242 if (!PrevInit) {
2243 PrevInit = Init;
2244 return false;
2245 }
2246
2247 if (FieldDecl *Field = Init->getMember())
2248 S.Diag(Init->getSourceLocation(),
2249 diag::err_multiple_mem_initialization)
2250 << Field->getDeclName()
2251 << Init->getSourceRange();
2252 else {
John McCallf4c73712011-01-19 06:33:43 +00002253 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002254 assert(BaseClass && "neither field nor base");
2255 S.Diag(Init->getSourceLocation(),
2256 diag::err_multiple_base_initialization)
2257 << QualType(BaseClass, 0)
2258 << Init->getSourceRange();
2259 }
2260 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2261 << 0 << PrevInit->getSourceRange();
2262
2263 return true;
2264}
2265
Sean Huntcbb67482011-01-08 20:30:50 +00002266typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002267typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2268
2269bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002270 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002271 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002272 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002273 RecordDecl *Parent = Field->getParent();
2274 if (!Parent->isAnonymousStructOrUnion())
2275 return false;
2276
2277 NamedDecl *Child = Field;
2278 do {
2279 if (Parent->isUnion()) {
2280 UnionEntry &En = Unions[Parent];
2281 if (En.first && En.first != Child) {
2282 S.Diag(Init->getSourceLocation(),
2283 diag::err_multiple_mem_union_initialization)
2284 << Field->getDeclName()
2285 << Init->getSourceRange();
2286 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2287 << 0 << En.second->getSourceRange();
2288 return true;
2289 } else if (!En.first) {
2290 En.first = Child;
2291 En.second = Init;
2292 }
2293 }
2294
2295 Child = Parent;
2296 Parent = cast<RecordDecl>(Parent->getDeclContext());
2297 } while (Parent->isAnonymousStructOrUnion());
2298
2299 return false;
2300}
2301}
2302
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002303/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002304void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002305 SourceLocation ColonLoc,
2306 MemInitTy **meminits, unsigned NumMemInits,
2307 bool AnyErrors) {
2308 if (!ConstructorDecl)
2309 return;
2310
2311 AdjustDeclIfTemplate(ConstructorDecl);
2312
2313 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002314 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002315
2316 if (!Constructor) {
2317 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2318 return;
2319 }
2320
Sean Huntcbb67482011-01-08 20:30:50 +00002321 CXXCtorInitializer **MemInits =
2322 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002323
2324 // Mapping for the duplicate initializers check.
2325 // For member initializers, this is keyed with a FieldDecl*.
2326 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002327 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002328
2329 // Mapping for the inconsistent anonymous-union initializers check.
2330 RedundantUnionMap MemberUnions;
2331
Anders Carlssonea356fb2010-04-02 05:42:15 +00002332 bool HadError = false;
2333 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002334 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002335
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002336 // Set the source order index.
2337 Init->setSourceOrder(i);
2338
Francois Pichet00eb3f92010-12-04 09:14:42 +00002339 if (Init->isAnyMemberInitializer()) {
2340 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002341 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2342 CheckRedundantUnionInit(*this, Init, MemberUnions))
2343 HadError = true;
2344 } else {
2345 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2346 if (CheckRedundantInit(*this, Init, Members[Key]))
2347 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002348 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002349 }
2350
Anders Carlssonea356fb2010-04-02 05:42:15 +00002351 if (HadError)
2352 return;
2353
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002354 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002355
Sean Huntcbb67482011-01-08 20:30:50 +00002356 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002357}
2358
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002359void
John McCallef027fe2010-03-16 21:39:52 +00002360Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2361 CXXRecordDecl *ClassDecl) {
2362 // Ignore dependent contexts.
2363 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002364 return;
John McCall58e6f342010-03-16 05:22:47 +00002365
2366 // FIXME: all the access-control diagnostics are positioned on the
2367 // field/base declaration. That's probably good; that said, the
2368 // user might reasonably want to know why the destructor is being
2369 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002370
Anders Carlsson9f853df2009-11-17 04:44:12 +00002371 // Non-static data members.
2372 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2373 E = ClassDecl->field_end(); I != E; ++I) {
2374 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002375 if (Field->isInvalidDecl())
2376 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002377 QualType FieldType = Context.getBaseElementType(Field->getType());
2378
2379 const RecordType* RT = FieldType->getAs<RecordType>();
2380 if (!RT)
2381 continue;
2382
2383 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2384 if (FieldClassDecl->hasTrivialDestructor())
2385 continue;
2386
Douglas Gregordb89f282010-07-01 22:47:18 +00002387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002388 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002389 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002390 << Field->getDeclName()
2391 << FieldType);
2392
John McCallef027fe2010-03-16 21:39:52 +00002393 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002394 }
2395
John McCall58e6f342010-03-16 05:22:47 +00002396 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2397
Anders Carlsson9f853df2009-11-17 04:44:12 +00002398 // Bases.
2399 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2400 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002401 // Bases are always records in a well-formed non-dependent class.
2402 const RecordType *RT = Base->getType()->getAs<RecordType>();
2403
2404 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002405 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002406 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002407
2408 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002409 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002410 if (BaseClassDecl->hasTrivialDestructor())
2411 continue;
John McCall58e6f342010-03-16 05:22:47 +00002412
Douglas Gregordb89f282010-07-01 22:47:18 +00002413 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002414
2415 // FIXME: caret should be on the start of the class name
2416 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002417 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002418 << Base->getType()
2419 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002420
John McCallef027fe2010-03-16 21:39:52 +00002421 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002422 }
2423
2424 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002425 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2426 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002427
2428 // Bases are always records in a well-formed non-dependent class.
2429 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2430
2431 // Ignore direct virtual bases.
2432 if (DirectVirtualBases.count(RT))
2433 continue;
2434
Anders Carlsson9f853df2009-11-17 04:44:12 +00002435 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002436 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002437 if (BaseClassDecl->hasTrivialDestructor())
2438 continue;
John McCall58e6f342010-03-16 05:22:47 +00002439
Douglas Gregordb89f282010-07-01 22:47:18 +00002440 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002441 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002442 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002443 << VBase->getType());
2444
John McCallef027fe2010-03-16 21:39:52 +00002445 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002446 }
2447}
2448
John McCalld226f652010-08-21 09:40:31 +00002449void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002450 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002451 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Mike Stump1eb44332009-09-09 15:08:12 +00002453 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002454 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002455 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002456}
2457
Mike Stump1eb44332009-09-09 15:08:12 +00002458bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002459 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002460 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002461 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002462 else
John McCall94c3b562010-08-18 09:41:07 +00002463 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002464}
2465
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002466bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002467 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002468 if (!getLangOptions().CPlusPlus)
2469 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Anders Carlsson11f21a02009-03-23 19:10:31 +00002471 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002472 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Ted Kremenek6217b802009-07-29 21:53:49 +00002474 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002475 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002476 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002477 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002479 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002480 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002481 }
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Ted Kremenek6217b802009-07-29 21:53:49 +00002483 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002484 if (!RT)
2485 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
John McCall86ff3082010-02-04 22:26:26 +00002487 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002488
John McCall94c3b562010-08-18 09:41:07 +00002489 // We can't answer whether something is abstract until it has a
2490 // definition. If it's currently being defined, we'll walk back
2491 // over all the declarations when we have a full definition.
2492 const CXXRecordDecl *Def = RD->getDefinition();
2493 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002494 return false;
2495
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002496 if (!RD->isAbstract())
2497 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002499 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002500 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002501
John McCall94c3b562010-08-18 09:41:07 +00002502 return true;
2503}
2504
2505void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2506 // Check if we've already emitted the list of pure virtual functions
2507 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002508 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002509 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002511 CXXFinalOverriderMap FinalOverriders;
2512 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002514 // Keep a set of seen pure methods so we won't diagnose the same method
2515 // more than once.
2516 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2517
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002518 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2519 MEnd = FinalOverriders.end();
2520 M != MEnd;
2521 ++M) {
2522 for (OverridingMethods::iterator SO = M->second.begin(),
2523 SOEnd = M->second.end();
2524 SO != SOEnd; ++SO) {
2525 // C++ [class.abstract]p4:
2526 // A class is abstract if it contains or inherits at least one
2527 // pure virtual function for which the final overrider is pure
2528 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002530 //
2531 if (SO->second.size() != 1)
2532 continue;
2533
2534 if (!SO->second.front().Method->isPure())
2535 continue;
2536
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002537 if (!SeenPureMethods.insert(SO->second.front().Method))
2538 continue;
2539
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002540 Diag(SO->second.front().Method->getLocation(),
2541 diag::note_pure_virtual_function)
2542 << SO->second.front().Method->getDeclName();
2543 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002544 }
2545
2546 if (!PureVirtualClassDiagSet)
2547 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2548 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002549}
2550
Anders Carlsson8211eff2009-03-24 01:19:16 +00002551namespace {
John McCall94c3b562010-08-18 09:41:07 +00002552struct AbstractUsageInfo {
2553 Sema &S;
2554 CXXRecordDecl *Record;
2555 CanQualType AbstractType;
2556 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002557
John McCall94c3b562010-08-18 09:41:07 +00002558 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2559 : S(S), Record(Record),
2560 AbstractType(S.Context.getCanonicalType(
2561 S.Context.getTypeDeclType(Record))),
2562 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002563
John McCall94c3b562010-08-18 09:41:07 +00002564 void DiagnoseAbstractType() {
2565 if (Invalid) return;
2566 S.DiagnoseAbstractType(Record);
2567 Invalid = true;
2568 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002569
John McCall94c3b562010-08-18 09:41:07 +00002570 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2571};
2572
2573struct CheckAbstractUsage {
2574 AbstractUsageInfo &Info;
2575 const NamedDecl *Ctx;
2576
2577 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2578 : Info(Info), Ctx(Ctx) {}
2579
2580 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2581 switch (TL.getTypeLocClass()) {
2582#define ABSTRACT_TYPELOC(CLASS, PARENT)
2583#define TYPELOC(CLASS, PARENT) \
2584 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2585#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002586 }
John McCall94c3b562010-08-18 09:41:07 +00002587 }
Mike Stump1eb44332009-09-09 15:08:12 +00002588
John McCall94c3b562010-08-18 09:41:07 +00002589 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2590 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2591 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2592 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2593 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002594 }
John McCall94c3b562010-08-18 09:41:07 +00002595 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002596
John McCall94c3b562010-08-18 09:41:07 +00002597 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2598 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2599 }
Mike Stump1eb44332009-09-09 15:08:12 +00002600
John McCall94c3b562010-08-18 09:41:07 +00002601 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2602 // Visit the type parameters from a permissive context.
2603 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2604 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2605 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2606 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2607 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2608 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002609 }
John McCall94c3b562010-08-18 09:41:07 +00002610 }
Mike Stump1eb44332009-09-09 15:08:12 +00002611
John McCall94c3b562010-08-18 09:41:07 +00002612 // Visit pointee types from a permissive context.
2613#define CheckPolymorphic(Type) \
2614 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2615 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2616 }
2617 CheckPolymorphic(PointerTypeLoc)
2618 CheckPolymorphic(ReferenceTypeLoc)
2619 CheckPolymorphic(MemberPointerTypeLoc)
2620 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002621
John McCall94c3b562010-08-18 09:41:07 +00002622 /// Handle all the types we haven't given a more specific
2623 /// implementation for above.
2624 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2625 // Every other kind of type that we haven't called out already
2626 // that has an inner type is either (1) sugar or (2) contains that
2627 // inner type in some way as a subobject.
2628 if (TypeLoc Next = TL.getNextTypeLoc())
2629 return Visit(Next, Sel);
2630
2631 // If there's no inner type and we're in a permissive context,
2632 // don't diagnose.
2633 if (Sel == Sema::AbstractNone) return;
2634
2635 // Check whether the type matches the abstract type.
2636 QualType T = TL.getType();
2637 if (T->isArrayType()) {
2638 Sel = Sema::AbstractArrayType;
2639 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002640 }
John McCall94c3b562010-08-18 09:41:07 +00002641 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2642 if (CT != Info.AbstractType) return;
2643
2644 // It matched; do some magic.
2645 if (Sel == Sema::AbstractArrayType) {
2646 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2647 << T << TL.getSourceRange();
2648 } else {
2649 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2650 << Sel << T << TL.getSourceRange();
2651 }
2652 Info.DiagnoseAbstractType();
2653 }
2654};
2655
2656void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2657 Sema::AbstractDiagSelID Sel) {
2658 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2659}
2660
2661}
2662
2663/// Check for invalid uses of an abstract type in a method declaration.
2664static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2665 CXXMethodDecl *MD) {
2666 // No need to do the check on definitions, which require that
2667 // the return/param types be complete.
2668 if (MD->isThisDeclarationADefinition())
2669 return;
2670
2671 // For safety's sake, just ignore it if we don't have type source
2672 // information. This should never happen for non-implicit methods,
2673 // but...
2674 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2675 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2676}
2677
2678/// Check for invalid uses of an abstract type within a class definition.
2679static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2680 CXXRecordDecl *RD) {
2681 for (CXXRecordDecl::decl_iterator
2682 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2683 Decl *D = *I;
2684 if (D->isImplicit()) continue;
2685
2686 // Methods and method templates.
2687 if (isa<CXXMethodDecl>(D)) {
2688 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2689 } else if (isa<FunctionTemplateDecl>(D)) {
2690 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2691 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2692
2693 // Fields and static variables.
2694 } else if (isa<FieldDecl>(D)) {
2695 FieldDecl *FD = cast<FieldDecl>(D);
2696 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2697 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2698 } else if (isa<VarDecl>(D)) {
2699 VarDecl *VD = cast<VarDecl>(D);
2700 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2701 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2702
2703 // Nested classes and class templates.
2704 } else if (isa<CXXRecordDecl>(D)) {
2705 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2706 } else if (isa<ClassTemplateDecl>(D)) {
2707 CheckAbstractClassUsage(Info,
2708 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2709 }
2710 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002711}
2712
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002713/// \brief Perform semantic checks on a class definition that has been
2714/// completing, introducing implicitly-declared members, checking for
2715/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002716void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002717 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002718 return;
2719
John McCall94c3b562010-08-18 09:41:07 +00002720 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2721 AbstractUsageInfo Info(*this, Record);
2722 CheckAbstractClassUsage(Info, Record);
2723 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002724
2725 // If this is not an aggregate type and has no user-declared constructor,
2726 // complain about any non-static data members of reference or const scalar
2727 // type, since they will never get initializers.
2728 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2729 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2730 bool Complained = false;
2731 for (RecordDecl::field_iterator F = Record->field_begin(),
2732 FEnd = Record->field_end();
2733 F != FEnd; ++F) {
2734 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002735 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002736 if (!Complained) {
2737 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2738 << Record->getTagKind() << Record;
2739 Complained = true;
2740 }
2741
2742 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2743 << F->getType()->isReferenceType()
2744 << F->getDeclName();
2745 }
2746 }
2747 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002748
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002749 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002750 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002751
2752 if (Record->getIdentifier()) {
2753 // C++ [class.mem]p13:
2754 // If T is the name of a class, then each of the following shall have a
2755 // name different from T:
2756 // - every member of every anonymous union that is a member of class T.
2757 //
2758 // C++ [class.mem]p14:
2759 // In addition, if class T has a user-declared constructor (12.1), every
2760 // non-static data member of class T shall have a name different from T.
2761 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002762 R.first != R.second; ++R.first) {
2763 NamedDecl *D = *R.first;
2764 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2765 isa<IndirectFieldDecl>(D)) {
2766 Diag(D->getLocation(), diag::err_member_name_of_class)
2767 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002768 break;
2769 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002770 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002771 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002772
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002773 // Warn if the class has virtual methods but non-virtual public destructor.
Argyrios Kyrtzidis668fdd82011-02-02 18:47:41 +00002774 if (Record->isDynamicClass() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002775 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002776 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002777 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2778 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2779 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002780
2781 // See if a method overloads virtual methods in a base
2782 /// class without overriding any.
2783 if (!Record->isDependentType()) {
2784 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2785 MEnd = Record->method_end();
2786 M != MEnd; ++M) {
2787 DiagnoseHiddenVirtualMethods(Record, *M);
2788 }
2789 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002790
2791 // Declare inherited constructors. We do this eagerly here because:
2792 // - The standard requires an eager diagnostic for conflicting inherited
2793 // constructors from different classes.
2794 // - The lazy declaration of the other implicit constructors is so as to not
2795 // waste space and performance on classes that are not meant to be
2796 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2797 // have inherited constructors.
2798 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002799}
2800
2801/// \brief Data used with FindHiddenVirtualMethod
2802struct FindHiddenVirtualMethodData {
2803 Sema *S;
2804 CXXMethodDecl *Method;
2805 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2806 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2807};
2808
2809/// \brief Member lookup function that determines whether a given C++
2810/// method overloads virtual methods in a base class without overriding any,
2811/// to be used with CXXRecordDecl::lookupInBases().
2812static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2813 CXXBasePath &Path,
2814 void *UserData) {
2815 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2816
2817 FindHiddenVirtualMethodData &Data
2818 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2819
2820 DeclarationName Name = Data.Method->getDeclName();
2821 assert(Name.getNameKind() == DeclarationName::Identifier);
2822
2823 bool foundSameNameMethod = false;
2824 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2825 for (Path.Decls = BaseRecord->lookup(Name);
2826 Path.Decls.first != Path.Decls.second;
2827 ++Path.Decls.first) {
2828 NamedDecl *D = *Path.Decls.first;
2829 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002830 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002831 foundSameNameMethod = true;
2832 // Interested only in hidden virtual methods.
2833 if (!MD->isVirtual())
2834 continue;
2835 // If the method we are checking overrides a method from its base
2836 // don't warn about the other overloaded methods.
2837 if (!Data.S->IsOverload(Data.Method, MD, false))
2838 return true;
2839 // Collect the overload only if its hidden.
2840 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2841 overloadedMethods.push_back(MD);
2842 }
2843 }
2844
2845 if (foundSameNameMethod)
2846 Data.OverloadedMethods.append(overloadedMethods.begin(),
2847 overloadedMethods.end());
2848 return foundSameNameMethod;
2849}
2850
2851/// \brief See if a method overloads virtual methods in a base class without
2852/// overriding any.
2853void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2854 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2855 MD->getLocation()) == Diagnostic::Ignored)
2856 return;
2857 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2858 return;
2859
2860 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2861 /*bool RecordPaths=*/false,
2862 /*bool DetectVirtual=*/false);
2863 FindHiddenVirtualMethodData Data;
2864 Data.Method = MD;
2865 Data.S = this;
2866
2867 // Keep the base methods that were overriden or introduced in the subclass
2868 // by 'using' in a set. A base method not in this set is hidden.
2869 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2870 res.first != res.second; ++res.first) {
2871 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2872 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2873 E = MD->end_overridden_methods();
2874 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002875 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002876 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2877 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002878 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002879 }
2880
2881 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2882 !Data.OverloadedMethods.empty()) {
2883 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2884 << MD << (Data.OverloadedMethods.size() > 1);
2885
2886 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2887 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2888 Diag(overloadedMD->getLocation(),
2889 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2890 }
2891 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002892}
2893
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002894void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002895 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002896 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002897 SourceLocation RBrac,
2898 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002899 if (!TagDecl)
2900 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002901
Douglas Gregor42af25f2009-05-11 19:58:34 +00002902 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002903
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002904 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002905 // strict aliasing violation!
2906 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002907 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002908
Douglas Gregor23c94db2010-07-02 17:43:08 +00002909 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002910 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002911}
2912
Douglas Gregord92ec472010-07-01 05:10:53 +00002913namespace {
2914 /// \brief Helper class that collects exception specifications for
2915 /// implicitly-declared special member functions.
2916 class ImplicitExceptionSpecification {
2917 ASTContext &Context;
2918 bool AllowsAllExceptions;
2919 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2920 llvm::SmallVector<QualType, 4> Exceptions;
2921
2922 public:
2923 explicit ImplicitExceptionSpecification(ASTContext &Context)
2924 : Context(Context), AllowsAllExceptions(false) { }
2925
2926 /// \brief Whether the special member function should have any
2927 /// exception specification at all.
2928 bool hasExceptionSpecification() const {
2929 return !AllowsAllExceptions;
2930 }
2931
2932 /// \brief Whether the special member function should have a
2933 /// throw(...) exception specification (a Microsoft extension).
2934 bool hasAnyExceptionSpecification() const {
2935 return false;
2936 }
2937
2938 /// \brief The number of exceptions in the exception specification.
2939 unsigned size() const { return Exceptions.size(); }
2940
2941 /// \brief The set of exceptions in the exception specification.
2942 const QualType *data() const { return Exceptions.data(); }
2943
2944 /// \brief Note that
2945 void CalledDecl(CXXMethodDecl *Method) {
2946 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002947 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002948 return;
2949
2950 const FunctionProtoType *Proto
2951 = Method->getType()->getAs<FunctionProtoType>();
2952
2953 // If this function can throw any exceptions, make a note of that.
2954 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2955 AllowsAllExceptions = true;
2956 ExceptionsSeen.clear();
2957 Exceptions.clear();
2958 return;
2959 }
2960
2961 // Record the exceptions in this function's exception specification.
2962 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2963 EEnd = Proto->exception_end();
2964 E != EEnd; ++E)
2965 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2966 Exceptions.push_back(*E);
2967 }
2968 };
2969}
2970
2971
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002972/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2973/// special functions, such as the default constructor, copy
2974/// constructor, or destructor, to the given C++ class (C++
2975/// [special]p1). This routine can only be executed just before the
2976/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002977void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002978 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002979 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002980
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002981 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002982 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002983
Douglas Gregora376d102010-07-02 21:50:04 +00002984 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2985 ++ASTContext::NumImplicitCopyAssignmentOperators;
2986
2987 // If we have a dynamic class, then the copy assignment operator may be
2988 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2989 // it shows up in the right place in the vtable and that we diagnose
2990 // problems with the implicit exception specification.
2991 if (ClassDecl->isDynamicClass())
2992 DeclareImplicitCopyAssignment(ClassDecl);
2993 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002994
Douglas Gregor4923aa22010-07-02 20:37:36 +00002995 if (!ClassDecl->hasUserDeclaredDestructor()) {
2996 ++ASTContext::NumImplicitDestructors;
2997
2998 // If we have a dynamic class, then the destructor may be virtual, so we
2999 // have to declare the destructor immediately. This ensures that, e.g., it
3000 // shows up in the right place in the vtable and that we diagnose problems
3001 // with the implicit exception specification.
3002 if (ClassDecl->isDynamicClass())
3003 DeclareImplicitDestructor(ClassDecl);
3004 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003005}
3006
John McCalld226f652010-08-21 09:40:31 +00003007void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003008 if (!D)
3009 return;
3010
3011 TemplateParameterList *Params = 0;
3012 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3013 Params = Template->getTemplateParameters();
3014 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3015 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3016 Params = PartialSpec->getTemplateParameters();
3017 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003018 return;
3019
Douglas Gregor6569d682009-05-27 23:11:45 +00003020 for (TemplateParameterList::iterator Param = Params->begin(),
3021 ParamEnd = Params->end();
3022 Param != ParamEnd; ++Param) {
3023 NamedDecl *Named = cast<NamedDecl>(*Param);
3024 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003025 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003026 IdResolver.AddDecl(Named);
3027 }
3028 }
3029}
3030
John McCalld226f652010-08-21 09:40:31 +00003031void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003032 if (!RecordD) return;
3033 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003034 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003035 PushDeclContext(S, Record);
3036}
3037
John McCalld226f652010-08-21 09:40:31 +00003038void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003039 if (!RecordD) return;
3040 PopDeclContext();
3041}
3042
Douglas Gregor72b505b2008-12-16 21:30:33 +00003043/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3044/// parsing a top-level (non-nested) C++ class, and we are now
3045/// parsing those parts of the given Method declaration that could
3046/// not be parsed earlier (C++ [class.mem]p2), such as default
3047/// arguments. This action should enter the scope of the given
3048/// Method declaration as if we had just parsed the qualified method
3049/// name. However, it should not bring the parameters into scope;
3050/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003051void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003052}
3053
3054/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3055/// C++ method declaration. We're (re-)introducing the given
3056/// function parameter into scope for use in parsing later parts of
3057/// the method declaration. For example, we could see an
3058/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003059void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003060 if (!ParamD)
3061 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003062
John McCalld226f652010-08-21 09:40:31 +00003063 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003064
3065 // If this parameter has an unparsed default argument, clear it out
3066 // to make way for the parsed default argument.
3067 if (Param->hasUnparsedDefaultArg())
3068 Param->setDefaultArg(0);
3069
John McCalld226f652010-08-21 09:40:31 +00003070 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003071 if (Param->getDeclName())
3072 IdResolver.AddDecl(Param);
3073}
3074
3075/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3076/// processing the delayed method declaration for Method. The method
3077/// declaration is now considered finished. There may be a separate
3078/// ActOnStartOfFunctionDef action later (not necessarily
3079/// immediately!) for this method, if it was also defined inside the
3080/// class body.
John McCalld226f652010-08-21 09:40:31 +00003081void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003082 if (!MethodD)
3083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003085 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003086
John McCalld226f652010-08-21 09:40:31 +00003087 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003088
3089 // Now that we have our default arguments, check the constructor
3090 // again. It could produce additional diagnostics or affect whether
3091 // the class has implicitly-declared destructors, among other
3092 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3094 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003095
3096 // Check the default arguments, which we may have added.
3097 if (!Method->isInvalidDecl())
3098 CheckCXXDefaultArguments(Method);
3099}
3100
Douglas Gregor42a552f2008-11-05 20:51:48 +00003101/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003102/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003103/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003104/// emit diagnostics and set the invalid bit to true. In any case, the type
3105/// will be updated to reflect a well-formed type for the constructor and
3106/// returned.
3107QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003108 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003109 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003110
3111 // C++ [class.ctor]p3:
3112 // A constructor shall not be virtual (10.3) or static (9.4). A
3113 // constructor can be invoked for a const, volatile or const
3114 // volatile object. A constructor shall not be declared const,
3115 // volatile, or const volatile (9.3.2).
3116 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003117 if (!D.isInvalidType())
3118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3119 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3120 << SourceRange(D.getIdentifierLoc());
3121 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003122 }
John McCalld931b082010-08-26 03:08:43 +00003123 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003124 if (!D.isInvalidType())
3125 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3126 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3127 << SourceRange(D.getIdentifierLoc());
3128 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003129 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003130 }
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003132 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003133 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003134 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003135 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3136 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003137 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003138 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3139 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003140 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3142 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003143 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003144 }
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Douglas Gregorc938c162011-01-26 05:01:58 +00003146 // C++0x [class.ctor]p4:
3147 // A constructor shall not be declared with a ref-qualifier.
3148 if (FTI.hasRefQualifier()) {
3149 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3150 << FTI.RefQualifierIsLValueRef
3151 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3152 D.setInvalidType();
3153 }
3154
Douglas Gregor42a552f2008-11-05 20:51:48 +00003155 // Rebuild the function type "R" without any type qualifiers (in
3156 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003157 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003158 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003159 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3160 return R;
3161
3162 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3163 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003164 EPI.RefQualifier = RQ_None;
3165
Chris Lattner65401802009-04-25 08:28:21 +00003166 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003167 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003168}
3169
Douglas Gregor72b505b2008-12-16 21:30:33 +00003170/// CheckConstructor - Checks a fully-formed constructor for
3171/// well-formedness, issuing any diagnostics required. Returns true if
3172/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003173void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003174 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003175 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3176 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003177 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003178
3179 // C++ [class.copy]p3:
3180 // A declaration of a constructor for a class X is ill-formed if
3181 // its first parameter is of type (optionally cv-qualified) X and
3182 // either there are no other parameters or else all other
3183 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003184 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003185 ((Constructor->getNumParams() == 1) ||
3186 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003187 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3188 Constructor->getTemplateSpecializationKind()
3189 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003190 QualType ParamType = Constructor->getParamDecl(0)->getType();
3191 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3192 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003193 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003194 const char *ConstRef
3195 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3196 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003197 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003198 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003199
3200 // FIXME: Rather that making the constructor invalid, we should endeavor
3201 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003202 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003203 }
3204 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003205}
3206
John McCall15442822010-08-04 01:04:25 +00003207/// CheckDestructor - Checks a fully-formed destructor definition for
3208/// well-formedness, issuing any diagnostics required. Returns true
3209/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003210bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003211 CXXRecordDecl *RD = Destructor->getParent();
3212
3213 if (Destructor->isVirtual()) {
3214 SourceLocation Loc;
3215
3216 if (!Destructor->isImplicit())
3217 Loc = Destructor->getLocation();
3218 else
3219 Loc = RD->getLocation();
3220
3221 // If we have a virtual destructor, look up the deallocation function
3222 FunctionDecl *OperatorDelete = 0;
3223 DeclarationName Name =
3224 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003225 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003226 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003227
3228 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003229
3230 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003231 }
Anders Carlsson37909802009-11-30 21:24:50 +00003232
3233 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003234}
3235
Mike Stump1eb44332009-09-09 15:08:12 +00003236static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003237FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3238 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3239 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003240 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003241}
3242
Douglas Gregor42a552f2008-11-05 20:51:48 +00003243/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3244/// the well-formednes of the destructor declarator @p D with type @p
3245/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003246/// emit diagnostics and set the declarator to invalid. Even if this happens,
3247/// will be updated to reflect a well-formed type for the destructor and
3248/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003249QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003250 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003251 // C++ [class.dtor]p1:
3252 // [...] A typedef-name that names a class is a class-name
3253 // (7.1.3); however, a typedef-name that names a class shall not
3254 // be used as the identifier in the declarator for a destructor
3255 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003256 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003257 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003258 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003259 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003260
3261 // C++ [class.dtor]p2:
3262 // A destructor is used to destroy objects of its class type. A
3263 // destructor takes no parameters, and no return type can be
3264 // specified for it (not even void). The address of a destructor
3265 // shall not be taken. A destructor shall not be static. A
3266 // destructor can be invoked for a const, volatile or const
3267 // volatile object. A destructor shall not be declared const,
3268 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003269 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003270 if (!D.isInvalidType())
3271 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3272 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003273 << SourceRange(D.getIdentifierLoc())
3274 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3275
John McCalld931b082010-08-26 03:08:43 +00003276 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003277 }
Chris Lattner65401802009-04-25 08:28:21 +00003278 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003279 // Destructors don't have return types, but the parser will
3280 // happily parse something like:
3281 //
3282 // class X {
3283 // float ~X();
3284 // };
3285 //
3286 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003287 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3288 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3289 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003290 }
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003292 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003293 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003294 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3296 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003297 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003298 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3299 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003300 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003301 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3302 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003303 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003304 }
3305
Douglas Gregorc938c162011-01-26 05:01:58 +00003306 // C++0x [class.dtor]p2:
3307 // A destructor shall not be declared with a ref-qualifier.
3308 if (FTI.hasRefQualifier()) {
3309 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3310 << FTI.RefQualifierIsLValueRef
3311 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3312 D.setInvalidType();
3313 }
3314
Douglas Gregor42a552f2008-11-05 20:51:48 +00003315 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003316 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003317 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3318
3319 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003320 FTI.freeArgs();
3321 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003322 }
3323
Mike Stump1eb44332009-09-09 15:08:12 +00003324 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003325 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003326 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003327 D.setInvalidType();
3328 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003329
3330 // Rebuild the function type "R" without any type qualifiers or
3331 // parameters (in case any of the errors above fired) and with
3332 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003333 // types.
John McCalle23cf432010-12-14 08:05:40 +00003334 if (!D.isInvalidType())
3335 return R;
3336
Douglas Gregord92ec472010-07-01 05:10:53 +00003337 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003338 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3339 EPI.Variadic = false;
3340 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003341 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003342 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003343}
3344
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003345/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3346/// well-formednes of the conversion function declarator @p D with
3347/// type @p R. If there are any errors in the declarator, this routine
3348/// will emit diagnostics and return true. Otherwise, it will return
3349/// false. Either way, the type @p R will be updated to reflect a
3350/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003351void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003352 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003353 // C++ [class.conv.fct]p1:
3354 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003355 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003356 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003357 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003358 if (!D.isInvalidType())
3359 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3360 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3361 << SourceRange(D.getIdentifierLoc());
3362 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003363 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003364 }
John McCalla3f81372010-04-13 00:04:31 +00003365
3366 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3367
Chris Lattner6e475012009-04-25 08:35:12 +00003368 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003369 // Conversion functions don't have return types, but the parser will
3370 // happily parse something like:
3371 //
3372 // class X {
3373 // float operator bool();
3374 // };
3375 //
3376 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003377 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3378 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3379 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003380 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003381 }
3382
John McCalla3f81372010-04-13 00:04:31 +00003383 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3384
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003385 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003386 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003387 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3388
3389 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003390 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003391 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003392 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003393 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003394 D.setInvalidType();
3395 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003396
John McCalla3f81372010-04-13 00:04:31 +00003397 // Diagnose "&operator bool()" and other such nonsense. This
3398 // is actually a gcc extension which we don't support.
3399 if (Proto->getResultType() != ConvType) {
3400 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3401 << Proto->getResultType();
3402 D.setInvalidType();
3403 ConvType = Proto->getResultType();
3404 }
3405
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003406 // C++ [class.conv.fct]p4:
3407 // The conversion-type-id shall not represent a function type nor
3408 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003409 if (ConvType->isArrayType()) {
3410 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3411 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003412 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003413 } else if (ConvType->isFunctionType()) {
3414 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3415 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003416 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003417 }
3418
3419 // Rebuild the function type "R" without any parameters (in case any
3420 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003421 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003422 if (D.isInvalidType())
3423 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003424
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003425 // C++0x explicit conversion operators.
3426 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003427 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003428 diag::warn_explicit_conversion_functions)
3429 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003430}
3431
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003432/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3433/// the declaration of the given C++ conversion function. This routine
3434/// is responsible for recording the conversion function in the C++
3435/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003436Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003437 assert(Conversion && "Expected to receive a conversion function declaration");
3438
Douglas Gregor9d350972008-12-12 08:25:50 +00003439 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003440
3441 // Make sure we aren't redeclaring the conversion function.
3442 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003443
3444 // C++ [class.conv.fct]p1:
3445 // [...] A conversion function is never used to convert a
3446 // (possibly cv-qualified) object to the (possibly cv-qualified)
3447 // same object type (or a reference to it), to a (possibly
3448 // cv-qualified) base class of that type (or a reference to it),
3449 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003450 // FIXME: Suppress this warning if the conversion function ends up being a
3451 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003452 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003453 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003454 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003455 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003456 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3457 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003458 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003459 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003460 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3461 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003462 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003463 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003464 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003465 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003466 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003467 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003468 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003469 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003470 }
3471
Douglas Gregore80622f2010-09-29 04:25:11 +00003472 if (FunctionTemplateDecl *ConversionTemplate
3473 = Conversion->getDescribedFunctionTemplate())
3474 return ConversionTemplate;
3475
John McCalld226f652010-08-21 09:40:31 +00003476 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003477}
3478
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003479//===----------------------------------------------------------------------===//
3480// Namespace Handling
3481//===----------------------------------------------------------------------===//
3482
John McCallea318642010-08-26 09:15:37 +00003483
3484
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003485/// ActOnStartNamespaceDef - This is called at the start of a namespace
3486/// definition.
John McCalld226f652010-08-21 09:40:31 +00003487Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003488 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003489 SourceLocation IdentLoc,
3490 IdentifierInfo *II,
3491 SourceLocation LBrace,
3492 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003493 // anonymous namespace starts at its left brace
3494 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3495 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003496 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003497 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003498
3499 Scope *DeclRegionScope = NamespcScope->getParent();
3500
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003501 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3502
John McCall90f14502010-12-10 02:59:44 +00003503 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3504 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003505
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003506 if (II) {
3507 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003508 // The identifier in an original-namespace-definition shall not
3509 // have been previously defined in the declarative region in
3510 // which the original-namespace-definition appears. The
3511 // identifier in an original-namespace-definition is the name of
3512 // the namespace. Subsequently in that declarative region, it is
3513 // treated as an original-namespace-name.
3514 //
3515 // Since namespace names are unique in their scope, and we don't
3516 // look through using directives, just
3517 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3518 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003519
Douglas Gregor44b43212008-12-11 16:49:14 +00003520 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3521 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003522 if (Namespc->isInline() != OrigNS->isInline()) {
3523 // inline-ness must match
3524 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3525 << Namespc->isInline();
3526 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3527 Namespc->setInvalidDecl();
3528 // Recover by ignoring the new namespace's inline status.
3529 Namespc->setInline(OrigNS->isInline());
3530 }
3531
Douglas Gregor44b43212008-12-11 16:49:14 +00003532 // Attach this namespace decl to the chain of extended namespace
3533 // definitions.
3534 OrigNS->setNextNamespace(Namespc);
3535 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003536
Mike Stump1eb44332009-09-09 15:08:12 +00003537 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003538 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003539 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003540 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003541 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003542 } else if (PrevDecl) {
3543 // This is an invalid name redefinition.
3544 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3545 << Namespc->getDeclName();
3546 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3547 Namespc->setInvalidDecl();
3548 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003549 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003550 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003551 // This is the first "real" definition of the namespace "std", so update
3552 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003553 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003554 // We had already defined a dummy namespace "std". Link this new
3555 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003556 StdNS->setNextNamespace(Namespc);
3557 StdNS->setLocation(IdentLoc);
3558 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003559 }
3560
3561 // Make our StdNamespace cache point at the first real definition of the
3562 // "std" namespace.
3563 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003564 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003565
3566 PushOnScopeChains(Namespc, DeclRegionScope);
3567 } else {
John McCall9aeed322009-10-01 00:25:31 +00003568 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003569 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003570
3571 // Link the anonymous namespace into its parent.
3572 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003573 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003574 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3575 PrevDecl = TU->getAnonymousNamespace();
3576 TU->setAnonymousNamespace(Namespc);
3577 } else {
3578 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3579 PrevDecl = ND->getAnonymousNamespace();
3580 ND->setAnonymousNamespace(Namespc);
3581 }
3582
3583 // Link the anonymous namespace with its previous declaration.
3584 if (PrevDecl) {
3585 assert(PrevDecl->isAnonymousNamespace());
3586 assert(!PrevDecl->getNextNamespace());
3587 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3588 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003589
3590 if (Namespc->isInline() != PrevDecl->isInline()) {
3591 // inline-ness must match
3592 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3593 << Namespc->isInline();
3594 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3595 Namespc->setInvalidDecl();
3596 // Recover by ignoring the new namespace's inline status.
3597 Namespc->setInline(PrevDecl->isInline());
3598 }
John McCall5fdd7642009-12-16 02:06:49 +00003599 }
John McCall9aeed322009-10-01 00:25:31 +00003600
Douglas Gregora4181472010-03-24 00:46:35 +00003601 CurContext->addDecl(Namespc);
3602
John McCall9aeed322009-10-01 00:25:31 +00003603 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3604 // behaves as if it were replaced by
3605 // namespace unique { /* empty body */ }
3606 // using namespace unique;
3607 // namespace unique { namespace-body }
3608 // where all occurrences of 'unique' in a translation unit are
3609 // replaced by the same identifier and this identifier differs
3610 // from all other identifiers in the entire program.
3611
3612 // We just create the namespace with an empty name and then add an
3613 // implicit using declaration, just like the standard suggests.
3614 //
3615 // CodeGen enforces the "universally unique" aspect by giving all
3616 // declarations semantically contained within an anonymous
3617 // namespace internal linkage.
3618
John McCall5fdd7642009-12-16 02:06:49 +00003619 if (!PrevDecl) {
3620 UsingDirectiveDecl* UD
3621 = UsingDirectiveDecl::Create(Context, CurContext,
3622 /* 'using' */ LBrace,
3623 /* 'namespace' */ SourceLocation(),
3624 /* qualifier */ SourceRange(),
3625 /* NNS */ NULL,
3626 /* identifier */ SourceLocation(),
3627 Namespc,
3628 /* Ancestor */ CurContext);
3629 UD->setImplicit();
3630 CurContext->addDecl(UD);
3631 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003632 }
3633
3634 // Although we could have an invalid decl (i.e. the namespace name is a
3635 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003636 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3637 // for the namespace has the declarations that showed up in that particular
3638 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003639 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003640 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003641}
3642
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003643/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3644/// is a namespace alias, returns the namespace it points to.
3645static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3646 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3647 return AD->getNamespace();
3648 return dyn_cast_or_null<NamespaceDecl>(D);
3649}
3650
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003651/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3652/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003653void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003654 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3655 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3656 Namespc->setRBracLoc(RBrace);
3657 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003658 if (Namespc->hasAttr<VisibilityAttr>())
3659 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003660}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003661
John McCall384aff82010-08-25 07:42:41 +00003662CXXRecordDecl *Sema::getStdBadAlloc() const {
3663 return cast_or_null<CXXRecordDecl>(
3664 StdBadAlloc.get(Context.getExternalSource()));
3665}
3666
3667NamespaceDecl *Sema::getStdNamespace() const {
3668 return cast_or_null<NamespaceDecl>(
3669 StdNamespace.get(Context.getExternalSource()));
3670}
3671
Douglas Gregor66992202010-06-29 17:53:46 +00003672/// \brief Retrieve the special "std" namespace, which may require us to
3673/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003674NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003675 if (!StdNamespace) {
3676 // The "std" namespace has not yet been defined, so build one implicitly.
3677 StdNamespace = NamespaceDecl::Create(Context,
3678 Context.getTranslationUnitDecl(),
3679 SourceLocation(),
3680 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003681 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003682 }
3683
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003684 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003685}
3686
John McCalld226f652010-08-21 09:40:31 +00003687Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003688 SourceLocation UsingLoc,
3689 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003690 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003691 SourceLocation IdentLoc,
3692 IdentifierInfo *NamespcName,
3693 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003694 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3695 assert(NamespcName && "Invalid NamespcName.");
3696 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003697
3698 // This can only happen along a recovery path.
3699 while (S->getFlags() & Scope::TemplateParamScope)
3700 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003701 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003702
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003703 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003704 NestedNameSpecifier *Qualifier = 0;
3705 if (SS.isSet())
3706 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3707
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003708 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003709 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3710 LookupParsedName(R, S, &SS);
3711 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003712 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003713
Douglas Gregor66992202010-06-29 17:53:46 +00003714 if (R.empty()) {
3715 // Allow "using namespace std;" or "using namespace ::std;" even if
3716 // "std" hasn't been defined yet, for GCC compatibility.
3717 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3718 NamespcName->isStr("std")) {
3719 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003720 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003721 R.resolveKind();
3722 }
3723 // Otherwise, attempt typo correction.
3724 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3725 CTC_NoKeywords, 0)) {
3726 if (R.getAsSingle<NamespaceDecl>() ||
3727 R.getAsSingle<NamespaceAliasDecl>()) {
3728 if (DeclContext *DC = computeDeclContext(SS, false))
3729 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3730 << NamespcName << DC << Corrected << SS.getRange()
3731 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3732 else
3733 Diag(IdentLoc, diag::err_using_directive_suggest)
3734 << NamespcName << Corrected
3735 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3736 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3737 << Corrected;
3738
3739 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003740 } else {
3741 R.clear();
3742 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003743 }
3744 }
3745 }
3746
John McCallf36e02d2009-10-09 21:13:30 +00003747 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003748 NamedDecl *Named = R.getFoundDecl();
3749 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3750 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003751 // C++ [namespace.udir]p1:
3752 // A using-directive specifies that the names in the nominated
3753 // namespace can be used in the scope in which the
3754 // using-directive appears after the using-directive. During
3755 // unqualified name lookup (3.4.1), the names appear as if they
3756 // were declared in the nearest enclosing namespace which
3757 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003758 // namespace. [Note: in this context, "contains" means "contains
3759 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003760
3761 // Find enclosing context containing both using-directive and
3762 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003763 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003764 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3765 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3766 CommonAncestor = CommonAncestor->getParent();
3767
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003768 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003769 SS.getRange(),
3770 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003771 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003772 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003773 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003774 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003775 }
3776
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003777 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003778 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003779}
3780
3781void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3782 // If scope has associated entity, then using directive is at namespace
3783 // or translation unit scope. We add UsingDirectiveDecls, into
3784 // it's lookup structure.
3785 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003786 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003787 else
3788 // Otherwise it is block-sope. using-directives will affect lookup
3789 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003790 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003791}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003792
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003793
John McCalld226f652010-08-21 09:40:31 +00003794Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003795 AccessSpecifier AS,
3796 bool HasUsingKeyword,
3797 SourceLocation UsingLoc,
3798 CXXScopeSpec &SS,
3799 UnqualifiedId &Name,
3800 AttributeList *AttrList,
3801 bool IsTypeName,
3802 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003803 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003804
Douglas Gregor12c118a2009-11-04 16:30:06 +00003805 switch (Name.getKind()) {
3806 case UnqualifiedId::IK_Identifier:
3807 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003808 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003809 case UnqualifiedId::IK_ConversionFunctionId:
3810 break;
3811
3812 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003813 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003814 // C++0x inherited constructors.
3815 if (getLangOptions().CPlusPlus0x) break;
3816
Douglas Gregor12c118a2009-11-04 16:30:06 +00003817 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3818 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003819 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003820
3821 case UnqualifiedId::IK_DestructorName:
3822 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3823 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003824 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003825
3826 case UnqualifiedId::IK_TemplateId:
3827 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3828 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003829 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003830 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003831
3832 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3833 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003834 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003835 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003836
John McCall60fa3cf2009-12-11 02:10:03 +00003837 // Warn about using declarations.
3838 // TODO: store that the declaration was written without 'using' and
3839 // talk about access decls instead of using decls in the
3840 // diagnostics.
3841 if (!HasUsingKeyword) {
3842 UsingLoc = Name.getSourceRange().getBegin();
3843
3844 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003845 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003846 }
3847
Douglas Gregor56c04582010-12-16 00:46:58 +00003848 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3849 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3850 return 0;
3851
John McCall9488ea12009-11-17 05:59:44 +00003852 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003853 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003854 /* IsInstantiation */ false,
3855 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003856 if (UD)
3857 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003858
John McCalld226f652010-08-21 09:40:31 +00003859 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003860}
3861
Douglas Gregor09acc982010-07-07 23:08:52 +00003862/// \brief Determine whether a using declaration considers the given
3863/// declarations as "equivalent", e.g., if they are redeclarations of
3864/// the same entity or are both typedefs of the same type.
3865static bool
3866IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3867 bool &SuppressRedeclaration) {
3868 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3869 SuppressRedeclaration = false;
3870 return true;
3871 }
3872
3873 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3874 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3875 SuppressRedeclaration = true;
3876 return Context.hasSameType(TD1->getUnderlyingType(),
3877 TD2->getUnderlyingType());
3878 }
3879
3880 return false;
3881}
3882
3883
John McCall9f54ad42009-12-10 09:41:52 +00003884/// Determines whether to create a using shadow decl for a particular
3885/// decl, given the set of decls existing prior to this using lookup.
3886bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3887 const LookupResult &Previous) {
3888 // Diagnose finding a decl which is not from a base class of the
3889 // current class. We do this now because there are cases where this
3890 // function will silently decide not to build a shadow decl, which
3891 // will pre-empt further diagnostics.
3892 //
3893 // We don't need to do this in C++0x because we do the check once on
3894 // the qualifier.
3895 //
3896 // FIXME: diagnose the following if we care enough:
3897 // struct A { int foo; };
3898 // struct B : A { using A::foo; };
3899 // template <class T> struct C : A {};
3900 // template <class T> struct D : C<T> { using B::foo; } // <---
3901 // This is invalid (during instantiation) in C++03 because B::foo
3902 // resolves to the using decl in B, which is not a base class of D<T>.
3903 // We can't diagnose it immediately because C<T> is an unknown
3904 // specialization. The UsingShadowDecl in D<T> then points directly
3905 // to A::foo, which will look well-formed when we instantiate.
3906 // The right solution is to not collapse the shadow-decl chain.
3907 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3908 DeclContext *OrigDC = Orig->getDeclContext();
3909
3910 // Handle enums and anonymous structs.
3911 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3912 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3913 while (OrigRec->isAnonymousStructOrUnion())
3914 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3915
3916 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3917 if (OrigDC == CurContext) {
3918 Diag(Using->getLocation(),
3919 diag::err_using_decl_nested_name_specifier_is_current_class)
3920 << Using->getNestedNameRange();
3921 Diag(Orig->getLocation(), diag::note_using_decl_target);
3922 return true;
3923 }
3924
3925 Diag(Using->getNestedNameRange().getBegin(),
3926 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3927 << Using->getTargetNestedNameDecl()
3928 << cast<CXXRecordDecl>(CurContext)
3929 << Using->getNestedNameRange();
3930 Diag(Orig->getLocation(), diag::note_using_decl_target);
3931 return true;
3932 }
3933 }
3934
3935 if (Previous.empty()) return false;
3936
3937 NamedDecl *Target = Orig;
3938 if (isa<UsingShadowDecl>(Target))
3939 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3940
John McCalld7533ec2009-12-11 02:33:26 +00003941 // If the target happens to be one of the previous declarations, we
3942 // don't have a conflict.
3943 //
3944 // FIXME: but we might be increasing its access, in which case we
3945 // should redeclare it.
3946 NamedDecl *NonTag = 0, *Tag = 0;
3947 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3948 I != E; ++I) {
3949 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003950 bool Result;
3951 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3952 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003953
3954 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3955 }
3956
John McCall9f54ad42009-12-10 09:41:52 +00003957 if (Target->isFunctionOrFunctionTemplate()) {
3958 FunctionDecl *FD;
3959 if (isa<FunctionTemplateDecl>(Target))
3960 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3961 else
3962 FD = cast<FunctionDecl>(Target);
3963
3964 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003965 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003966 case Ovl_Overload:
3967 return false;
3968
3969 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003970 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003971 break;
3972
3973 // We found a decl with the exact signature.
3974 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003975 // If we're in a record, we want to hide the target, so we
3976 // return true (without a diagnostic) to tell the caller not to
3977 // build a shadow decl.
3978 if (CurContext->isRecord())
3979 return true;
3980
3981 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003982 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003983 break;
3984 }
3985
3986 Diag(Target->getLocation(), diag::note_using_decl_target);
3987 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3988 return true;
3989 }
3990
3991 // Target is not a function.
3992
John McCall9f54ad42009-12-10 09:41:52 +00003993 if (isa<TagDecl>(Target)) {
3994 // No conflict between a tag and a non-tag.
3995 if (!Tag) return false;
3996
John McCall41ce66f2009-12-10 19:51:03 +00003997 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003998 Diag(Target->getLocation(), diag::note_using_decl_target);
3999 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4000 return true;
4001 }
4002
4003 // No conflict between a tag and a non-tag.
4004 if (!NonTag) return false;
4005
John McCall41ce66f2009-12-10 19:51:03 +00004006 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004007 Diag(Target->getLocation(), diag::note_using_decl_target);
4008 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4009 return true;
4010}
4011
John McCall9488ea12009-11-17 05:59:44 +00004012/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004013UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004014 UsingDecl *UD,
4015 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004016
4017 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004018 NamedDecl *Target = Orig;
4019 if (isa<UsingShadowDecl>(Target)) {
4020 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4021 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004022 }
4023
4024 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004025 = UsingShadowDecl::Create(Context, CurContext,
4026 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004027 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004028
4029 Shadow->setAccess(UD->getAccess());
4030 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4031 Shadow->setInvalidDecl();
4032
John McCall9488ea12009-11-17 05:59:44 +00004033 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004034 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004035 else
John McCall604e7f12009-12-08 07:46:18 +00004036 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004037
John McCall604e7f12009-12-08 07:46:18 +00004038
John McCall9f54ad42009-12-10 09:41:52 +00004039 return Shadow;
4040}
John McCall604e7f12009-12-08 07:46:18 +00004041
John McCall9f54ad42009-12-10 09:41:52 +00004042/// Hides a using shadow declaration. This is required by the current
4043/// using-decl implementation when a resolvable using declaration in a
4044/// class is followed by a declaration which would hide or override
4045/// one or more of the using decl's targets; for example:
4046///
4047/// struct Base { void foo(int); };
4048/// struct Derived : Base {
4049/// using Base::foo;
4050/// void foo(int);
4051/// };
4052///
4053/// The governing language is C++03 [namespace.udecl]p12:
4054///
4055/// When a using-declaration brings names from a base class into a
4056/// derived class scope, member functions in the derived class
4057/// override and/or hide member functions with the same name and
4058/// parameter types in a base class (rather than conflicting).
4059///
4060/// There are two ways to implement this:
4061/// (1) optimistically create shadow decls when they're not hidden
4062/// by existing declarations, or
4063/// (2) don't create any shadow decls (or at least don't make them
4064/// visible) until we've fully parsed/instantiated the class.
4065/// The problem with (1) is that we might have to retroactively remove
4066/// a shadow decl, which requires several O(n) operations because the
4067/// decl structures are (very reasonably) not designed for removal.
4068/// (2) avoids this but is very fiddly and phase-dependent.
4069void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004070 if (Shadow->getDeclName().getNameKind() ==
4071 DeclarationName::CXXConversionFunctionName)
4072 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4073
John McCall9f54ad42009-12-10 09:41:52 +00004074 // Remove it from the DeclContext...
4075 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004076
John McCall9f54ad42009-12-10 09:41:52 +00004077 // ...and the scope, if applicable...
4078 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004079 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004080 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004081 }
4082
John McCall9f54ad42009-12-10 09:41:52 +00004083 // ...and the using decl.
4084 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4085
4086 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004087 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004088}
4089
John McCall7ba107a2009-11-18 02:36:19 +00004090/// Builds a using declaration.
4091///
4092/// \param IsInstantiation - Whether this call arises from an
4093/// instantiation of an unresolved using declaration. We treat
4094/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004095NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4096 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004097 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004098 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004099 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004100 bool IsInstantiation,
4101 bool IsTypeName,
4102 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004103 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004104 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004105 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004106
Anders Carlsson550b14b2009-08-28 05:49:21 +00004107 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004109 if (SS.isEmpty()) {
4110 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004111 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004112 }
Mike Stump1eb44332009-09-09 15:08:12 +00004113
John McCall9f54ad42009-12-10 09:41:52 +00004114 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004115 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004116 ForRedeclaration);
4117 Previous.setHideTags(false);
4118 if (S) {
4119 LookupName(Previous, S);
4120
4121 // It is really dumb that we have to do this.
4122 LookupResult::Filter F = Previous.makeFilter();
4123 while (F.hasNext()) {
4124 NamedDecl *D = F.next();
4125 if (!isDeclInScope(D, CurContext, S))
4126 F.erase();
4127 }
4128 F.done();
4129 } else {
4130 assert(IsInstantiation && "no scope in non-instantiation");
4131 assert(CurContext->isRecord() && "scope not record in instantiation");
4132 LookupQualifiedName(Previous, CurContext);
4133 }
4134
Sebastian Redlf677ea32011-02-05 19:23:19 +00004135 NestedNameSpecifier *NNS = SS.getScopeRep();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004136
John McCall9f54ad42009-12-10 09:41:52 +00004137 // Check for invalid redeclarations.
4138 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4139 return 0;
4140
4141 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004142 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4143 return 0;
4144
John McCallaf8e6ed2009-11-12 03:15:40 +00004145 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004146 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00004147 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004148 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004149 // FIXME: not all declaration name kinds are legal here
4150 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4151 UsingLoc, TypenameLoc,
4152 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004153 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004154 } else {
4155 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004156 UsingLoc, SS.getRange(),
4157 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004158 }
John McCalled976492009-12-04 22:46:56 +00004159 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004160 D = UsingDecl::Create(Context, CurContext,
4161 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00004162 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004163 }
John McCalled976492009-12-04 22:46:56 +00004164 D->setAccess(AS);
4165 CurContext->addDecl(D);
4166
4167 if (!LookupContext) return D;
4168 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004169
John McCall77bb1aa2010-05-01 00:40:08 +00004170 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004171 UD->setInvalidDecl();
4172 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004173 }
4174
Sebastian Redlf677ea32011-02-05 19:23:19 +00004175 // Constructor inheriting using decls get special treatment.
4176 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4177 if (CheckInheritedConstructorUsingDecl(UD))
4178 UD->setInvalidDecl();
4179 return UD;
4180 }
4181
4182 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004183
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004184 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004185
John McCall604e7f12009-12-08 07:46:18 +00004186 // Unlike most lookups, we don't always want to hide tag
4187 // declarations: tag names are visible through the using declaration
4188 // even if hidden by ordinary names, *except* in a dependent context
4189 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004190 if (!IsInstantiation)
4191 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004192
John McCalla24dc2e2009-11-17 02:14:36 +00004193 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004194
John McCallf36e02d2009-10-09 21:13:30 +00004195 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004196 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004197 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004198 UD->setInvalidDecl();
4199 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004200 }
4201
John McCalled976492009-12-04 22:46:56 +00004202 if (R.isAmbiguous()) {
4203 UD->setInvalidDecl();
4204 return UD;
4205 }
Mike Stump1eb44332009-09-09 15:08:12 +00004206
John McCall7ba107a2009-11-18 02:36:19 +00004207 if (IsTypeName) {
4208 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004209 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004210 Diag(IdentLoc, diag::err_using_typename_non_type);
4211 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4212 Diag((*I)->getUnderlyingDecl()->getLocation(),
4213 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004214 UD->setInvalidDecl();
4215 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004216 }
4217 } else {
4218 // If we asked for a non-typename and we got a type, error out,
4219 // but only if this is an instantiation of an unresolved using
4220 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004221 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004222 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4223 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004224 UD->setInvalidDecl();
4225 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004226 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004227 }
4228
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004229 // C++0x N2914 [namespace.udecl]p6:
4230 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004231 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004232 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4233 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004234 UD->setInvalidDecl();
4235 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004236 }
Mike Stump1eb44332009-09-09 15:08:12 +00004237
John McCall9f54ad42009-12-10 09:41:52 +00004238 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4239 if (!CheckUsingShadowDecl(UD, *I, Previous))
4240 BuildUsingShadowDecl(S, UD, *I);
4241 }
John McCall9488ea12009-11-17 05:59:44 +00004242
4243 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004244}
4245
Sebastian Redlf677ea32011-02-05 19:23:19 +00004246/// Additional checks for a using declaration referring to a constructor name.
4247bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4248 if (UD->isTypeName()) {
4249 // FIXME: Cannot specify typename when specifying constructor
4250 return true;
4251 }
4252
4253 const Type *SourceType = UD->getTargetNestedNameDecl()->getAsType();
4254 assert(SourceType &&
4255 "Using decl naming constructor doesn't have type in scope spec.");
4256 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4257
4258 // Check whether the named type is a direct base class.
4259 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4260 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4261 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4262 BaseIt != BaseE; ++BaseIt) {
4263 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4264 if (CanonicalSourceType == BaseType)
4265 break;
4266 }
4267
4268 if (BaseIt == BaseE) {
4269 // Did not find SourceType in the bases.
4270 Diag(UD->getUsingLocation(),
4271 diag::err_using_decl_constructor_not_in_direct_base)
4272 << UD->getNameInfo().getSourceRange()
4273 << QualType(SourceType, 0) << TargetClass;
4274 return true;
4275 }
4276
4277 BaseIt->setInheritConstructors();
4278
4279 return false;
4280}
4281
John McCall9f54ad42009-12-10 09:41:52 +00004282/// Checks that the given using declaration is not an invalid
4283/// redeclaration. Note that this is checking only for the using decl
4284/// itself, not for any ill-formedness among the UsingShadowDecls.
4285bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4286 bool isTypeName,
4287 const CXXScopeSpec &SS,
4288 SourceLocation NameLoc,
4289 const LookupResult &Prev) {
4290 // C++03 [namespace.udecl]p8:
4291 // C++0x [namespace.udecl]p10:
4292 // A using-declaration is a declaration and can therefore be used
4293 // repeatedly where (and only where) multiple declarations are
4294 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004295 //
John McCall8a726212010-11-29 18:01:58 +00004296 // That's in non-member contexts.
4297 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004298 return false;
4299
4300 NestedNameSpecifier *Qual
4301 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4302
4303 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4304 NamedDecl *D = *I;
4305
4306 bool DTypename;
4307 NestedNameSpecifier *DQual;
4308 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4309 DTypename = UD->isTypeName();
4310 DQual = UD->getTargetNestedNameDecl();
4311 } else if (UnresolvedUsingValueDecl *UD
4312 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4313 DTypename = false;
4314 DQual = UD->getTargetNestedNameSpecifier();
4315 } else if (UnresolvedUsingTypenameDecl *UD
4316 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4317 DTypename = true;
4318 DQual = UD->getTargetNestedNameSpecifier();
4319 } else continue;
4320
4321 // using decls differ if one says 'typename' and the other doesn't.
4322 // FIXME: non-dependent using decls?
4323 if (isTypeName != DTypename) continue;
4324
4325 // using decls differ if they name different scopes (but note that
4326 // template instantiation can cause this check to trigger when it
4327 // didn't before instantiation).
4328 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4329 Context.getCanonicalNestedNameSpecifier(DQual))
4330 continue;
4331
4332 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004333 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004334 return true;
4335 }
4336
4337 return false;
4338}
4339
John McCall604e7f12009-12-08 07:46:18 +00004340
John McCalled976492009-12-04 22:46:56 +00004341/// Checks that the given nested-name qualifier used in a using decl
4342/// in the current context is appropriately related to the current
4343/// scope. If an error is found, diagnoses it and returns true.
4344bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4345 const CXXScopeSpec &SS,
4346 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004347 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004348
John McCall604e7f12009-12-08 07:46:18 +00004349 if (!CurContext->isRecord()) {
4350 // C++03 [namespace.udecl]p3:
4351 // C++0x [namespace.udecl]p8:
4352 // A using-declaration for a class member shall be a member-declaration.
4353
4354 // If we weren't able to compute a valid scope, it must be a
4355 // dependent class scope.
4356 if (!NamedContext || NamedContext->isRecord()) {
4357 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4358 << SS.getRange();
4359 return true;
4360 }
4361
4362 // Otherwise, everything is known to be fine.
4363 return false;
4364 }
4365
4366 // The current scope is a record.
4367
4368 // If the named context is dependent, we can't decide much.
4369 if (!NamedContext) {
4370 // FIXME: in C++0x, we can diagnose if we can prove that the
4371 // nested-name-specifier does not refer to a base class, which is
4372 // still possible in some cases.
4373
4374 // Otherwise we have to conservatively report that things might be
4375 // okay.
4376 return false;
4377 }
4378
4379 if (!NamedContext->isRecord()) {
4380 // Ideally this would point at the last name in the specifier,
4381 // but we don't have that level of source info.
4382 Diag(SS.getRange().getBegin(),
4383 diag::err_using_decl_nested_name_specifier_is_not_class)
4384 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4385 return true;
4386 }
4387
Douglas Gregor6fb07292010-12-21 07:41:49 +00004388 if (!NamedContext->isDependentContext() &&
4389 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4390 return true;
4391
John McCall604e7f12009-12-08 07:46:18 +00004392 if (getLangOptions().CPlusPlus0x) {
4393 // C++0x [namespace.udecl]p3:
4394 // In a using-declaration used as a member-declaration, the
4395 // nested-name-specifier shall name a base class of the class
4396 // being defined.
4397
4398 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4399 cast<CXXRecordDecl>(NamedContext))) {
4400 if (CurContext == NamedContext) {
4401 Diag(NameLoc,
4402 diag::err_using_decl_nested_name_specifier_is_current_class)
4403 << SS.getRange();
4404 return true;
4405 }
4406
4407 Diag(SS.getRange().getBegin(),
4408 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4409 << (NestedNameSpecifier*) SS.getScopeRep()
4410 << cast<CXXRecordDecl>(CurContext)
4411 << SS.getRange();
4412 return true;
4413 }
4414
4415 return false;
4416 }
4417
4418 // C++03 [namespace.udecl]p4:
4419 // A using-declaration used as a member-declaration shall refer
4420 // to a member of a base class of the class being defined [etc.].
4421
4422 // Salient point: SS doesn't have to name a base class as long as
4423 // lookup only finds members from base classes. Therefore we can
4424 // diagnose here only if we can prove that that can't happen,
4425 // i.e. if the class hierarchies provably don't intersect.
4426
4427 // TODO: it would be nice if "definitely valid" results were cached
4428 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4429 // need to be repeated.
4430
4431 struct UserData {
4432 llvm::DenseSet<const CXXRecordDecl*> Bases;
4433
4434 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4435 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4436 Data->Bases.insert(Base);
4437 return true;
4438 }
4439
4440 bool hasDependentBases(const CXXRecordDecl *Class) {
4441 return !Class->forallBases(collect, this);
4442 }
4443
4444 /// Returns true if the base is dependent or is one of the
4445 /// accumulated base classes.
4446 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4447 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4448 return !Data->Bases.count(Base);
4449 }
4450
4451 bool mightShareBases(const CXXRecordDecl *Class) {
4452 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4453 }
4454 };
4455
4456 UserData Data;
4457
4458 // Returns false if we find a dependent base.
4459 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4460 return false;
4461
4462 // Returns false if the class has a dependent base or if it or one
4463 // of its bases is present in the base set of the current context.
4464 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4465 return false;
4466
4467 Diag(SS.getRange().getBegin(),
4468 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4469 << (NestedNameSpecifier*) SS.getScopeRep()
4470 << cast<CXXRecordDecl>(CurContext)
4471 << SS.getRange();
4472
4473 return true;
John McCalled976492009-12-04 22:46:56 +00004474}
4475
John McCalld226f652010-08-21 09:40:31 +00004476Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004477 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004478 SourceLocation AliasLoc,
4479 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004480 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004481 SourceLocation IdentLoc,
4482 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Anders Carlsson81c85c42009-03-28 23:53:49 +00004484 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004485 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4486 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004487
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004488 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004489 NamedDecl *PrevDecl
4490 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4491 ForRedeclaration);
4492 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4493 PrevDecl = 0;
4494
4495 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004496 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004497 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004498 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004499 // FIXME: At some point, we'll want to create the (redundant)
4500 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004501 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004502 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004503 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004504 }
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004506 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4507 diag::err_redefinition_different_kind;
4508 Diag(AliasLoc, DiagID) << Alias;
4509 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004510 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004511 }
4512
John McCalla24dc2e2009-11-17 02:14:36 +00004513 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004514 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004515
John McCallf36e02d2009-10-09 21:13:30 +00004516 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004517 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4518 CTC_NoKeywords, 0)) {
4519 if (R.getAsSingle<NamespaceDecl>() ||
4520 R.getAsSingle<NamespaceAliasDecl>()) {
4521 if (DeclContext *DC = computeDeclContext(SS, false))
4522 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4523 << Ident << DC << Corrected << SS.getRange()
4524 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4525 else
4526 Diag(IdentLoc, diag::err_using_directive_suggest)
4527 << Ident << Corrected
4528 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4529
4530 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4531 << Corrected;
4532
4533 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004534 } else {
4535 R.clear();
4536 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004537 }
4538 }
4539
4540 if (R.empty()) {
4541 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004542 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004543 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004544 }
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004546 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004547 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4548 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004549 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004550 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004551
John McCall3dbd3d52010-02-16 06:53:13 +00004552 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004553 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004554}
4555
Douglas Gregor39957dc2010-05-01 15:04:51 +00004556namespace {
4557 /// \brief Scoped object used to handle the state changes required in Sema
4558 /// to implicitly define the body of a C++ member function;
4559 class ImplicitlyDefinedFunctionScope {
4560 Sema &S;
4561 DeclContext *PreviousContext;
4562
4563 public:
4564 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4565 : S(S), PreviousContext(S.CurContext)
4566 {
4567 S.CurContext = Method;
4568 S.PushFunctionScope();
4569 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4570 }
4571
4572 ~ImplicitlyDefinedFunctionScope() {
4573 S.PopExpressionEvaluationContext();
4574 S.PopFunctionOrBlockScope();
4575 S.CurContext = PreviousContext;
4576 }
4577 };
4578}
4579
Sebastian Redl751025d2010-09-13 22:02:47 +00004580static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4581 CXXRecordDecl *D) {
4582 ASTContext &Context = Self.Context;
4583 QualType ClassType = Context.getTypeDeclType(D);
4584 DeclarationName ConstructorName
4585 = Context.DeclarationNames.getCXXConstructorName(
4586 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4587
4588 DeclContext::lookup_const_iterator Con, ConEnd;
4589 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4590 Con != ConEnd; ++Con) {
4591 // FIXME: In C++0x, a constructor template can be a default constructor.
4592 if (isa<FunctionTemplateDecl>(*Con))
4593 continue;
4594
4595 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4596 if (Constructor->isDefaultConstructor())
4597 return Constructor;
4598 }
4599 return 0;
4600}
4601
Douglas Gregor23c94db2010-07-02 17:43:08 +00004602CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4603 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004604 // C++ [class.ctor]p5:
4605 // A default constructor for a class X is a constructor of class X
4606 // that can be called without an argument. If there is no
4607 // user-declared constructor for class X, a default constructor is
4608 // implicitly declared. An implicitly-declared default constructor
4609 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004610 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4611 "Should not build implicit default constructor!");
4612
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004613 // C++ [except.spec]p14:
4614 // An implicitly declared special member function (Clause 12) shall have an
4615 // exception-specification. [...]
4616 ImplicitExceptionSpecification ExceptSpec(Context);
4617
4618 // Direct base-class destructors.
4619 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4620 BEnd = ClassDecl->bases_end();
4621 B != BEnd; ++B) {
4622 if (B->isVirtual()) // Handled below.
4623 continue;
4624
Douglas Gregor18274032010-07-03 00:47:00 +00004625 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4626 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4627 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4628 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004629 else if (CXXConstructorDecl *Constructor
4630 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004631 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004632 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004633 }
4634
4635 // Virtual base-class destructors.
4636 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4637 BEnd = ClassDecl->vbases_end();
4638 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004639 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4640 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4641 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4642 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4643 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004644 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004645 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004646 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004647 }
4648
4649 // Field destructors.
4650 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4651 FEnd = ClassDecl->field_end();
4652 F != FEnd; ++F) {
4653 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004654 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4655 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4656 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4657 ExceptSpec.CalledDecl(
4658 DeclareImplicitDefaultConstructor(FieldClassDecl));
4659 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004660 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004661 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004662 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004663 }
John McCalle23cf432010-12-14 08:05:40 +00004664
4665 FunctionProtoType::ExtProtoInfo EPI;
4666 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4667 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4668 EPI.NumExceptions = ExceptSpec.size();
4669 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004670
4671 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004672 CanQualType ClassType
4673 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4674 DeclarationName Name
4675 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004676 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004677 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004678 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004679 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004680 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004681 /*TInfo=*/0,
4682 /*isExplicit=*/false,
4683 /*isInline=*/true,
4684 /*isImplicitlyDeclared=*/true);
4685 DefaultCon->setAccess(AS_public);
4686 DefaultCon->setImplicit();
4687 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004688
4689 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004690 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4691
Douglas Gregor23c94db2010-07-02 17:43:08 +00004692 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004693 PushOnScopeChains(DefaultCon, S, false);
4694 ClassDecl->addDecl(DefaultCon);
4695
Douglas Gregor32df23e2010-07-01 22:02:46 +00004696 return DefaultCon;
4697}
4698
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004699void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4700 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004701 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004702 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004703 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004705 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004706 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004707
Douglas Gregor39957dc2010-05-01 15:04:51 +00004708 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004709 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004710 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004711 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004712 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004713 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004714 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004715 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004716 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004717
4718 SourceLocation Loc = Constructor->getLocation();
4719 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4720
4721 Constructor->setUsed();
4722 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004723}
4724
Sebastian Redlf677ea32011-02-05 19:23:19 +00004725void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4726 // We start with an initial pass over the base classes to collect those that
4727 // inherit constructors from. If there are none, we can forgo all further
4728 // processing.
4729 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4730 BasesVector BasesToInheritFrom;
4731 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4732 BaseE = ClassDecl->bases_end();
4733 BaseIt != BaseE; ++BaseIt) {
4734 if (BaseIt->getInheritConstructors()) {
4735 QualType Base = BaseIt->getType();
4736 if (Base->isDependentType()) {
4737 // If we inherit constructors from anything that is dependent, just
4738 // abort processing altogether. We'll get another chance for the
4739 // instantiations.
4740 return;
4741 }
4742 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4743 }
4744 }
4745 if (BasesToInheritFrom.empty())
4746 return;
4747
4748 // Now collect the constructors that we already have in the current class.
4749 // Those take precedence over inherited constructors.
4750 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4751 // unless there is a user-declared constructor with the same signature in
4752 // the class where the using-declaration appears.
4753 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4754 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4755 CtorE = ClassDecl->ctor_end();
4756 CtorIt != CtorE; ++CtorIt) {
4757 ExistingConstructors.insert(
4758 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4759 }
4760
4761 Scope *S = getScopeForContext(ClassDecl);
4762 DeclarationName CreatedCtorName =
4763 Context.DeclarationNames.getCXXConstructorName(
4764 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4765
4766 // Now comes the true work.
4767 // First, we keep a map from constructor types to the base that introduced
4768 // them. Needed for finding conflicting constructors. We also keep the
4769 // actually inserted declarations in there, for pretty diagnostics.
4770 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4771 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4772 ConstructorToSourceMap InheritedConstructors;
4773 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4774 BaseE = BasesToInheritFrom.end();
4775 BaseIt != BaseE; ++BaseIt) {
4776 const RecordType *Base = *BaseIt;
4777 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4778 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4779 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4780 CtorE = BaseDecl->ctor_end();
4781 CtorIt != CtorE; ++CtorIt) {
4782 // Find the using declaration for inheriting this base's constructors.
4783 DeclarationName Name =
4784 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4785 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4786 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4787 SourceLocation UsingLoc = UD ? UD->getLocation() :
4788 ClassDecl->getLocation();
4789
4790 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4791 // from the class X named in the using-declaration consists of actual
4792 // constructors and notional constructors that result from the
4793 // transformation of defaulted parameters as follows:
4794 // - all non-template default constructors of X, and
4795 // - for each non-template constructor of X that has at least one
4796 // parameter with a default argument, the set of constructors that
4797 // results from omitting any ellipsis parameter specification and
4798 // successively omitting parameters with a default argument from the
4799 // end of the parameter-type-list.
4800 CXXConstructorDecl *BaseCtor = *CtorIt;
4801 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4802 const FunctionProtoType *BaseCtorType =
4803 BaseCtor->getType()->getAs<FunctionProtoType>();
4804
4805 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4806 maxParams = BaseCtor->getNumParams();
4807 params <= maxParams; ++params) {
4808 // Skip default constructors. They're never inherited.
4809 if (params == 0)
4810 continue;
4811 // Skip copy and move constructors for the same reason.
4812 if (CanBeCopyOrMove && params == 1)
4813 continue;
4814
4815 // Build up a function type for this particular constructor.
4816 // FIXME: The working paper does not consider that the exception spec
4817 // for the inheriting constructor might be larger than that of the
4818 // source. This code doesn't yet, either.
4819 const Type *NewCtorType;
4820 if (params == maxParams)
4821 NewCtorType = BaseCtorType;
4822 else {
4823 llvm::SmallVector<QualType, 16> Args;
4824 for (unsigned i = 0; i < params; ++i) {
4825 Args.push_back(BaseCtorType->getArgType(i));
4826 }
4827 FunctionProtoType::ExtProtoInfo ExtInfo =
4828 BaseCtorType->getExtProtoInfo();
4829 ExtInfo.Variadic = false;
4830 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4831 Args.data(), params, ExtInfo)
4832 .getTypePtr();
4833 }
4834 const Type *CanonicalNewCtorType =
4835 Context.getCanonicalType(NewCtorType);
4836
4837 // Now that we have the type, first check if the class already has a
4838 // constructor with this signature.
4839 if (ExistingConstructors.count(CanonicalNewCtorType))
4840 continue;
4841
4842 // Then we check if we have already declared an inherited constructor
4843 // with this signature.
4844 std::pair<ConstructorToSourceMap::iterator, bool> result =
4845 InheritedConstructors.insert(std::make_pair(
4846 CanonicalNewCtorType,
4847 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
4848 if (!result.second) {
4849 // Already in the map. If it came from a different class, that's an
4850 // error. Not if it's from the same.
4851 CanQualType PreviousBase = result.first->second.first;
4852 if (CanonicalBase != PreviousBase) {
4853 const CXXConstructorDecl *PrevCtor = result.first->second.second;
4854 const CXXConstructorDecl *PrevBaseCtor =
4855 PrevCtor->getInheritedConstructor();
4856 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
4857
4858 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
4859 Diag(BaseCtor->getLocation(),
4860 diag::note_using_decl_constructor_conflict_current_ctor);
4861 Diag(PrevBaseCtor->getLocation(),
4862 diag::note_using_decl_constructor_conflict_previous_ctor);
4863 Diag(PrevCtor->getLocation(),
4864 diag::note_using_decl_constructor_conflict_previous_using);
4865 }
4866 continue;
4867 }
4868
4869 // OK, we're there, now add the constructor.
4870 // C++0x [class.inhctor]p8: [...] that would be performed by a
4871 // user-writtern inline constructor [...]
4872 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
4873 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
4874 Context, ClassDecl, DNI, QualType(NewCtorType, 0), /*TInfo=*/0,
4875 BaseCtor->isExplicit(), /*Inline=*/true,
4876 /*ImplicitlyDeclared=*/true);
4877 NewCtor->setAccess(BaseCtor->getAccess());
4878
4879 // Build up the parameter decls and add them.
4880 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
4881 for (unsigned i = 0; i < params; ++i) {
4882 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, UsingLoc,
4883 /*IdentifierInfo=*/0,
4884 BaseCtorType->getArgType(i),
4885 /*TInfo=*/0, SC_None,
4886 SC_None, /*DefaultArg=*/0));
4887 }
4888 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
4889 NewCtor->setInheritedConstructor(BaseCtor);
4890
4891 PushOnScopeChains(NewCtor, S, false);
4892 ClassDecl->addDecl(NewCtor);
4893 result.first->second.second = NewCtor;
4894 }
4895 }
4896 }
4897}
4898
Douglas Gregor23c94db2010-07-02 17:43:08 +00004899CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004900 // C++ [class.dtor]p2:
4901 // If a class has no user-declared destructor, a destructor is
4902 // declared implicitly. An implicitly-declared destructor is an
4903 // inline public member of its class.
4904
4905 // C++ [except.spec]p14:
4906 // An implicitly declared special member function (Clause 12) shall have
4907 // an exception-specification.
4908 ImplicitExceptionSpecification ExceptSpec(Context);
4909
4910 // Direct base-class destructors.
4911 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4912 BEnd = ClassDecl->bases_end();
4913 B != BEnd; ++B) {
4914 if (B->isVirtual()) // Handled below.
4915 continue;
4916
4917 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4918 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004919 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004920 }
4921
4922 // Virtual base-class destructors.
4923 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4924 BEnd = ClassDecl->vbases_end();
4925 B != BEnd; ++B) {
4926 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4927 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004928 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004929 }
4930
4931 // Field destructors.
4932 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4933 FEnd = ClassDecl->field_end();
4934 F != FEnd; ++F) {
4935 if (const RecordType *RecordTy
4936 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4937 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004938 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004939 }
4940
Douglas Gregor4923aa22010-07-02 20:37:36 +00004941 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004942 FunctionProtoType::ExtProtoInfo EPI;
4943 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4944 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4945 EPI.NumExceptions = ExceptSpec.size();
4946 EPI.Exceptions = ExceptSpec.data();
4947 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004948
4949 CanQualType ClassType
4950 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4951 DeclarationName Name
4952 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004953 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004954 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004955 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004956 /*isInline=*/true,
4957 /*isImplicitlyDeclared=*/true);
4958 Destructor->setAccess(AS_public);
4959 Destructor->setImplicit();
4960 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004961
4962 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004963 ++ASTContext::NumImplicitDestructorsDeclared;
4964
4965 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004966 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004967 PushOnScopeChains(Destructor, S, false);
4968 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004969
4970 // This could be uniqued if it ever proves significant.
4971 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4972
4973 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004974
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004975 return Destructor;
4976}
4977
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004978void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004979 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004980 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004981 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004982 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004983 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004984
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004985 if (Destructor->isInvalidDecl())
4986 return;
4987
Douglas Gregor39957dc2010-05-01 15:04:51 +00004988 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004989
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004990 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004991 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4992 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004993
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004994 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004995 Diag(CurrentLocation, diag::note_member_synthesized_at)
4996 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4997
4998 Destructor->setInvalidDecl();
4999 return;
5000 }
5001
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005002 SourceLocation Loc = Destructor->getLocation();
5003 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5004
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005005 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005006 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005007}
5008
Douglas Gregor06a9f362010-05-01 20:49:11 +00005009/// \brief Builds a statement that copies the given entity from \p From to
5010/// \c To.
5011///
5012/// This routine is used to copy the members of a class with an
5013/// implicitly-declared copy assignment operator. When the entities being
5014/// copied are arrays, this routine builds for loops to copy them.
5015///
5016/// \param S The Sema object used for type-checking.
5017///
5018/// \param Loc The location where the implicit copy is being generated.
5019///
5020/// \param T The type of the expressions being copied. Both expressions must
5021/// have this type.
5022///
5023/// \param To The expression we are copying to.
5024///
5025/// \param From The expression we are copying from.
5026///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005027/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5028/// Otherwise, it's a non-static member subobject.
5029///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005030/// \param Depth Internal parameter recording the depth of the recursion.
5031///
5032/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005033static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005034BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005035 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005036 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005037 // C++0x [class.copy]p30:
5038 // Each subobject is assigned in the manner appropriate to its type:
5039 //
5040 // - if the subobject is of class type, the copy assignment operator
5041 // for the class is used (as if by explicit qualification; that is,
5042 // ignoring any possible virtual overriding functions in more derived
5043 // classes);
5044 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5045 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5046
5047 // Look for operator=.
5048 DeclarationName Name
5049 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5050 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5051 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5052
5053 // Filter out any result that isn't a copy-assignment operator.
5054 LookupResult::Filter F = OpLookup.makeFilter();
5055 while (F.hasNext()) {
5056 NamedDecl *D = F.next();
5057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5058 if (Method->isCopyAssignmentOperator())
5059 continue;
5060
5061 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005062 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005063 F.done();
5064
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005065 // Suppress the protected check (C++ [class.protected]) for each of the
5066 // assignment operators we found. This strange dance is required when
5067 // we're assigning via a base classes's copy-assignment operator. To
5068 // ensure that we're getting the right base class subobject (without
5069 // ambiguities), we need to cast "this" to that subobject type; to
5070 // ensure that we don't go through the virtual call mechanism, we need
5071 // to qualify the operator= name with the base class (see below). However,
5072 // this means that if the base class has a protected copy assignment
5073 // operator, the protected member access check will fail. So, we
5074 // rewrite "protected" access to "public" access in this case, since we
5075 // know by construction that we're calling from a derived class.
5076 if (CopyingBaseSubobject) {
5077 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5078 L != LEnd; ++L) {
5079 if (L.getAccess() == AS_protected)
5080 L.setAccess(AS_public);
5081 }
5082 }
5083
Douglas Gregor06a9f362010-05-01 20:49:11 +00005084 // Create the nested-name-specifier that will be used to qualify the
5085 // reference to operator=; this is required to suppress the virtual
5086 // call mechanism.
5087 CXXScopeSpec SS;
5088 SS.setRange(Loc);
5089 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
5090 T.getTypePtr()));
5091
5092 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005093 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005094 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005095 /*FirstQualifierInScope=*/0, OpLookup,
5096 /*TemplateArgs=*/0,
5097 /*SuppressQualifierCheck=*/true);
5098 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005099 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005100
5101 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005102
John McCall60d7b3a2010-08-24 06:29:42 +00005103 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005104 OpEqualRef.takeAs<Expr>(),
5105 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005106 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005107 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005108
5109 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005110 }
John McCallb0207482010-03-16 06:11:48 +00005111
Douglas Gregor06a9f362010-05-01 20:49:11 +00005112 // - if the subobject is of scalar type, the built-in assignment
5113 // operator is used.
5114 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5115 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005116 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005117 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005118 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005119
5120 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005121 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005122
5123 // - if the subobject is an array, each element is assigned, in the
5124 // manner appropriate to the element type;
5125
5126 // Construct a loop over the array bounds, e.g.,
5127 //
5128 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5129 //
5130 // that will copy each of the array elements.
5131 QualType SizeType = S.Context.getSizeType();
5132
5133 // Create the iteration variable.
5134 IdentifierInfo *IterationVarName = 0;
5135 {
5136 llvm::SmallString<8> Str;
5137 llvm::raw_svector_ostream OS(Str);
5138 OS << "__i" << Depth;
5139 IterationVarName = &S.Context.Idents.get(OS.str());
5140 }
5141 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
5142 IterationVarName, SizeType,
5143 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005144 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005145
5146 // Initialize the iteration variable to zero.
5147 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005148 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005149
5150 // Create a reference to the iteration variable; we'll use this several
5151 // times throughout.
5152 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005153 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005154 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5155
5156 // Create the DeclStmt that holds the iteration variable.
5157 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5158
5159 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005160 llvm::APInt Upper
5161 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005162 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005163 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005164 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5165 BO_NE, S.Context.BoolTy,
5166 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005167
5168 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005169 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005170 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5171 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005172
5173 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005174 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5175 IterationVarRef, Loc));
5176 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5177 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005178
5179 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005180 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5181 To, From, CopyingBaseSubobject,
5182 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005183 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005184 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005185
5186 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005187 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005188 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005189 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005190 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005191}
5192
Douglas Gregora376d102010-07-02 21:50:04 +00005193/// \brief Determine whether the given class has a copy assignment operator
5194/// that accepts a const-qualified argument.
5195static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5196 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5197
5198 if (!Class->hasDeclaredCopyAssignment())
5199 S.DeclareImplicitCopyAssignment(Class);
5200
5201 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5202 DeclarationName OpName
5203 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5204
5205 DeclContext::lookup_const_iterator Op, OpEnd;
5206 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5207 // C++ [class.copy]p9:
5208 // A user-declared copy assignment operator is a non-static non-template
5209 // member function of class X with exactly one parameter of type X, X&,
5210 // const X&, volatile X& or const volatile X&.
5211 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5212 if (!Method)
5213 continue;
5214
5215 if (Method->isStatic())
5216 continue;
5217 if (Method->getPrimaryTemplate())
5218 continue;
5219 const FunctionProtoType *FnType =
5220 Method->getType()->getAs<FunctionProtoType>();
5221 assert(FnType && "Overloaded operator has no prototype.");
5222 // Don't assert on this; an invalid decl might have been left in the AST.
5223 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5224 continue;
5225 bool AcceptsConst = true;
5226 QualType ArgType = FnType->getArgType(0);
5227 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5228 ArgType = Ref->getPointeeType();
5229 // Is it a non-const lvalue reference?
5230 if (!ArgType.isConstQualified())
5231 AcceptsConst = false;
5232 }
5233 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5234 continue;
5235
5236 // We have a single argument of type cv X or cv X&, i.e. we've found the
5237 // copy assignment operator. Return whether it accepts const arguments.
5238 return AcceptsConst;
5239 }
5240 assert(Class->isInvalidDecl() &&
5241 "No copy assignment operator declared in valid code.");
5242 return false;
5243}
5244
Douglas Gregor23c94db2010-07-02 17:43:08 +00005245CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005246 // Note: The following rules are largely analoguous to the copy
5247 // constructor rules. Note that virtual bases are not taken into account
5248 // for determining the argument type of the operator. Note also that
5249 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005250
5251
Douglas Gregord3c35902010-07-01 16:36:15 +00005252 // C++ [class.copy]p10:
5253 // If the class definition does not explicitly declare a copy
5254 // assignment operator, one is declared implicitly.
5255 // The implicitly-defined copy assignment operator for a class X
5256 // will have the form
5257 //
5258 // X& X::operator=(const X&)
5259 //
5260 // if
5261 bool HasConstCopyAssignment = true;
5262
5263 // -- each direct base class B of X has a copy assignment operator
5264 // whose parameter is of type const B&, const volatile B& or B,
5265 // and
5266 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5267 BaseEnd = ClassDecl->bases_end();
5268 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5269 assert(!Base->getType()->isDependentType() &&
5270 "Cannot generate implicit members for class with dependent bases.");
5271 const CXXRecordDecl *BaseClassDecl
5272 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005273 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005274 }
5275
5276 // -- for all the nonstatic data members of X that are of a class
5277 // type M (or array thereof), each such class type has a copy
5278 // assignment operator whose parameter is of type const M&,
5279 // const volatile M& or M.
5280 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5281 FieldEnd = ClassDecl->field_end();
5282 HasConstCopyAssignment && Field != FieldEnd;
5283 ++Field) {
5284 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5285 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5286 const CXXRecordDecl *FieldClassDecl
5287 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005288 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005289 }
5290 }
5291
5292 // Otherwise, the implicitly declared copy assignment operator will
5293 // have the form
5294 //
5295 // X& X::operator=(X&)
5296 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5297 QualType RetType = Context.getLValueReferenceType(ArgType);
5298 if (HasConstCopyAssignment)
5299 ArgType = ArgType.withConst();
5300 ArgType = Context.getLValueReferenceType(ArgType);
5301
Douglas Gregorb87786f2010-07-01 17:48:08 +00005302 // C++ [except.spec]p14:
5303 // An implicitly declared special member function (Clause 12) shall have an
5304 // exception-specification. [...]
5305 ImplicitExceptionSpecification ExceptSpec(Context);
5306 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5307 BaseEnd = ClassDecl->bases_end();
5308 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005309 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005310 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005311
5312 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5313 DeclareImplicitCopyAssignment(BaseClassDecl);
5314
Douglas Gregorb87786f2010-07-01 17:48:08 +00005315 if (CXXMethodDecl *CopyAssign
5316 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5317 ExceptSpec.CalledDecl(CopyAssign);
5318 }
5319 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5320 FieldEnd = ClassDecl->field_end();
5321 Field != FieldEnd;
5322 ++Field) {
5323 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5324 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005325 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005326 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005327
5328 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5329 DeclareImplicitCopyAssignment(FieldClassDecl);
5330
Douglas Gregorb87786f2010-07-01 17:48:08 +00005331 if (CXXMethodDecl *CopyAssign
5332 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5333 ExceptSpec.CalledDecl(CopyAssign);
5334 }
5335 }
5336
Douglas Gregord3c35902010-07-01 16:36:15 +00005337 // An implicitly-declared copy assignment operator is an inline public
5338 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005339 FunctionProtoType::ExtProtoInfo EPI;
5340 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5341 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5342 EPI.NumExceptions = ExceptSpec.size();
5343 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005344 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00005345 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005346 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00005347 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005348 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005349 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005350 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00005351 /*isInline=*/true);
5352 CopyAssignment->setAccess(AS_public);
5353 CopyAssignment->setImplicit();
5354 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005355
5356 // Add the parameter to the operator.
5357 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5358 ClassDecl->getLocation(),
5359 /*Id=*/0,
5360 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005361 SC_None,
5362 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005363 CopyAssignment->setParams(&FromParam, 1);
5364
Douglas Gregora376d102010-07-02 21:50:04 +00005365 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005366 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5367
Douglas Gregor23c94db2010-07-02 17:43:08 +00005368 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005369 PushOnScopeChains(CopyAssignment, S, false);
5370 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005371
5372 AddOverriddenMethods(ClassDecl, CopyAssignment);
5373 return CopyAssignment;
5374}
5375
Douglas Gregor06a9f362010-05-01 20:49:11 +00005376void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5377 CXXMethodDecl *CopyAssignOperator) {
5378 assert((CopyAssignOperator->isImplicit() &&
5379 CopyAssignOperator->isOverloadedOperator() &&
5380 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005381 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005382 "DefineImplicitCopyAssignment called for wrong function");
5383
5384 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5385
5386 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5387 CopyAssignOperator->setInvalidDecl();
5388 return;
5389 }
5390
5391 CopyAssignOperator->setUsed();
5392
5393 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005394 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005395
5396 // C++0x [class.copy]p30:
5397 // The implicitly-defined or explicitly-defaulted copy assignment operator
5398 // for a non-union class X performs memberwise copy assignment of its
5399 // subobjects. The direct base classes of X are assigned first, in the
5400 // order of their declaration in the base-specifier-list, and then the
5401 // immediate non-static data members of X are assigned, in the order in
5402 // which they were declared in the class definition.
5403
5404 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005405 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005406
5407 // The parameter for the "other" object, which we are copying from.
5408 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5409 Qualifiers OtherQuals = Other->getType().getQualifiers();
5410 QualType OtherRefType = Other->getType();
5411 if (const LValueReferenceType *OtherRef
5412 = OtherRefType->getAs<LValueReferenceType>()) {
5413 OtherRefType = OtherRef->getPointeeType();
5414 OtherQuals = OtherRefType.getQualifiers();
5415 }
5416
5417 // Our location for everything implicitly-generated.
5418 SourceLocation Loc = CopyAssignOperator->getLocation();
5419
5420 // Construct a reference to the "other" object. We'll be using this
5421 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005422 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005423 assert(OtherRef && "Reference to parameter cannot fail!");
5424
5425 // Construct the "this" pointer. We'll be using this throughout the generated
5426 // ASTs.
5427 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5428 assert(This && "Reference to this cannot fail!");
5429
5430 // Assign base classes.
5431 bool Invalid = false;
5432 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5433 E = ClassDecl->bases_end(); Base != E; ++Base) {
5434 // Form the assignment:
5435 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5436 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005437 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005438 Invalid = true;
5439 continue;
5440 }
5441
John McCallf871d0c2010-08-07 06:22:56 +00005442 CXXCastPath BasePath;
5443 BasePath.push_back(Base);
5444
Douglas Gregor06a9f362010-05-01 20:49:11 +00005445 // Construct the "from" expression, which is an implicit cast to the
5446 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005447 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005448 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005449 CK_UncheckedDerivedToBase,
5450 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005451
5452 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005453 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005454
5455 // Implicitly cast "this" to the appropriately-qualified base type.
5456 Expr *ToE = To.takeAs<Expr>();
5457 ImpCastExprToType(ToE,
5458 Context.getCVRQualifiedType(BaseType,
5459 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005460 CK_UncheckedDerivedToBase,
5461 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005462 To = Owned(ToE);
5463
5464 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005465 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005466 To.get(), From,
5467 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005468 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005469 Diag(CurrentLocation, diag::note_member_synthesized_at)
5470 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5471 CopyAssignOperator->setInvalidDecl();
5472 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005473 }
5474
5475 // Success! Record the copy.
5476 Statements.push_back(Copy.takeAs<Expr>());
5477 }
5478
5479 // \brief Reference to the __builtin_memcpy function.
5480 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005481 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005482 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005483
5484 // Assign non-static members.
5485 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5486 FieldEnd = ClassDecl->field_end();
5487 Field != FieldEnd; ++Field) {
5488 // Check for members of reference type; we can't copy those.
5489 if (Field->getType()->isReferenceType()) {
5490 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5491 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5492 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005493 Diag(CurrentLocation, diag::note_member_synthesized_at)
5494 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005495 Invalid = true;
5496 continue;
5497 }
5498
5499 // Check for members of const-qualified, non-class type.
5500 QualType BaseType = Context.getBaseElementType(Field->getType());
5501 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5502 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5503 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5504 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005505 Diag(CurrentLocation, diag::note_member_synthesized_at)
5506 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005507 Invalid = true;
5508 continue;
5509 }
5510
5511 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005512 if (FieldType->isIncompleteArrayType()) {
5513 assert(ClassDecl->hasFlexibleArrayMember() &&
5514 "Incomplete array type is not valid");
5515 continue;
5516 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005517
5518 // Build references to the field in the object we're copying from and to.
5519 CXXScopeSpec SS; // Intentionally empty
5520 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5521 LookupMemberName);
5522 MemberLookup.addDecl(*Field);
5523 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005524 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005525 Loc, /*IsArrow=*/false,
5526 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005527 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005528 Loc, /*IsArrow=*/true,
5529 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005530 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5531 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5532
5533 // If the field should be copied with __builtin_memcpy rather than via
5534 // explicit assignments, do so. This optimization only applies for arrays
5535 // of scalars and arrays of class type with trivial copy-assignment
5536 // operators.
5537 if (FieldType->isArrayType() &&
5538 (!BaseType->isRecordType() ||
5539 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5540 ->hasTrivialCopyAssignment())) {
5541 // Compute the size of the memory buffer to be copied.
5542 QualType SizeType = Context.getSizeType();
5543 llvm::APInt Size(Context.getTypeSize(SizeType),
5544 Context.getTypeSizeInChars(BaseType).getQuantity());
5545 for (const ConstantArrayType *Array
5546 = Context.getAsConstantArrayType(FieldType);
5547 Array;
5548 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005549 llvm::APInt ArraySize
5550 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005551 Size *= ArraySize;
5552 }
5553
5554 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005555 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5556 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005557
5558 bool NeedsCollectableMemCpy =
5559 (BaseType->isRecordType() &&
5560 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5561
5562 if (NeedsCollectableMemCpy) {
5563 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005564 // Create a reference to the __builtin_objc_memmove_collectable function.
5565 LookupResult R(*this,
5566 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005567 Loc, LookupOrdinaryName);
5568 LookupName(R, TUScope, true);
5569
5570 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5571 if (!CollectableMemCpy) {
5572 // Something went horribly wrong earlier, and we will have
5573 // complained about it.
5574 Invalid = true;
5575 continue;
5576 }
5577
5578 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5579 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005580 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005581 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5582 }
5583 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005584 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005585 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005586 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5587 LookupOrdinaryName);
5588 LookupName(R, TUScope, true);
5589
5590 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5591 if (!BuiltinMemCpy) {
5592 // Something went horribly wrong earlier, and we will have complained
5593 // about it.
5594 Invalid = true;
5595 continue;
5596 }
5597
5598 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5599 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005600 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005601 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5602 }
5603
John McCallca0408f2010-08-23 06:44:23 +00005604 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005605 CallArgs.push_back(To.takeAs<Expr>());
5606 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005607 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005608 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005609 if (NeedsCollectableMemCpy)
5610 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005611 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005612 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005613 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005614 else
5615 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005616 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005617 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005618 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005619
Douglas Gregor06a9f362010-05-01 20:49:11 +00005620 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5621 Statements.push_back(Call.takeAs<Expr>());
5622 continue;
5623 }
5624
5625 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005626 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005627 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005628 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005629 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005630 Diag(CurrentLocation, diag::note_member_synthesized_at)
5631 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5632 CopyAssignOperator->setInvalidDecl();
5633 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005634 }
5635
5636 // Success! Record the copy.
5637 Statements.push_back(Copy.takeAs<Stmt>());
5638 }
5639
5640 if (!Invalid) {
5641 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005642 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005643
John McCall60d7b3a2010-08-24 06:29:42 +00005644 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005645 if (Return.isInvalid())
5646 Invalid = true;
5647 else {
5648 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005649
5650 if (Trap.hasErrorOccurred()) {
5651 Diag(CurrentLocation, diag::note_member_synthesized_at)
5652 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5653 Invalid = true;
5654 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005655 }
5656 }
5657
5658 if (Invalid) {
5659 CopyAssignOperator->setInvalidDecl();
5660 return;
5661 }
5662
John McCall60d7b3a2010-08-24 06:29:42 +00005663 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005664 /*isStmtExpr=*/false);
5665 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5666 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005667}
5668
Douglas Gregor23c94db2010-07-02 17:43:08 +00005669CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5670 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005671 // C++ [class.copy]p4:
5672 // If the class definition does not explicitly declare a copy
5673 // constructor, one is declared implicitly.
5674
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005675 // C++ [class.copy]p5:
5676 // The implicitly-declared copy constructor for a class X will
5677 // have the form
5678 //
5679 // X::X(const X&)
5680 //
5681 // if
5682 bool HasConstCopyConstructor = true;
5683
5684 // -- each direct or virtual base class B of X has a copy
5685 // constructor whose first parameter is of type const B& or
5686 // const volatile B&, and
5687 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5688 BaseEnd = ClassDecl->bases_end();
5689 HasConstCopyConstructor && Base != BaseEnd;
5690 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005691 // Virtual bases are handled below.
5692 if (Base->isVirtual())
5693 continue;
5694
Douglas Gregor22584312010-07-02 23:41:54 +00005695 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005696 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005697 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5698 DeclareImplicitCopyConstructor(BaseClassDecl);
5699
Douglas Gregor598a8542010-07-01 18:27:03 +00005700 HasConstCopyConstructor
5701 = BaseClassDecl->hasConstCopyConstructor(Context);
5702 }
5703
5704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5705 BaseEnd = ClassDecl->vbases_end();
5706 HasConstCopyConstructor && Base != BaseEnd;
5707 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005708 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005709 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005710 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5711 DeclareImplicitCopyConstructor(BaseClassDecl);
5712
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005713 HasConstCopyConstructor
5714 = BaseClassDecl->hasConstCopyConstructor(Context);
5715 }
5716
5717 // -- for all the nonstatic data members of X that are of a
5718 // class type M (or array thereof), each such class type
5719 // has a copy constructor whose first parameter is of type
5720 // const M& or const volatile M&.
5721 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5722 FieldEnd = ClassDecl->field_end();
5723 HasConstCopyConstructor && Field != FieldEnd;
5724 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005725 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005726 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005727 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005728 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005729 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5730 DeclareImplicitCopyConstructor(FieldClassDecl);
5731
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005732 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005733 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005734 }
5735 }
5736
5737 // Otherwise, the implicitly declared copy constructor will have
5738 // the form
5739 //
5740 // X::X(X&)
5741 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5742 QualType ArgType = ClassType;
5743 if (HasConstCopyConstructor)
5744 ArgType = ArgType.withConst();
5745 ArgType = Context.getLValueReferenceType(ArgType);
5746
Douglas Gregor0d405db2010-07-01 20:59:04 +00005747 // C++ [except.spec]p14:
5748 // An implicitly declared special member function (Clause 12) shall have an
5749 // exception-specification. [...]
5750 ImplicitExceptionSpecification ExceptSpec(Context);
5751 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5753 BaseEnd = ClassDecl->bases_end();
5754 Base != BaseEnd;
5755 ++Base) {
5756 // Virtual bases are handled below.
5757 if (Base->isVirtual())
5758 continue;
5759
Douglas Gregor22584312010-07-02 23:41:54 +00005760 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005762 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5763 DeclareImplicitCopyConstructor(BaseClassDecl);
5764
Douglas Gregor0d405db2010-07-01 20:59:04 +00005765 if (CXXConstructorDecl *CopyConstructor
5766 = BaseClassDecl->getCopyConstructor(Context, Quals))
5767 ExceptSpec.CalledDecl(CopyConstructor);
5768 }
5769 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5770 BaseEnd = ClassDecl->vbases_end();
5771 Base != BaseEnd;
5772 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005773 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005774 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005775 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5776 DeclareImplicitCopyConstructor(BaseClassDecl);
5777
Douglas Gregor0d405db2010-07-01 20:59:04 +00005778 if (CXXConstructorDecl *CopyConstructor
5779 = BaseClassDecl->getCopyConstructor(Context, Quals))
5780 ExceptSpec.CalledDecl(CopyConstructor);
5781 }
5782 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5783 FieldEnd = ClassDecl->field_end();
5784 Field != FieldEnd;
5785 ++Field) {
5786 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5787 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005788 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005789 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005790 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5791 DeclareImplicitCopyConstructor(FieldClassDecl);
5792
Douglas Gregor0d405db2010-07-01 20:59:04 +00005793 if (CXXConstructorDecl *CopyConstructor
5794 = FieldClassDecl->getCopyConstructor(Context, Quals))
5795 ExceptSpec.CalledDecl(CopyConstructor);
5796 }
5797 }
5798
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005799 // An implicitly-declared copy constructor is an inline public
5800 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005801 FunctionProtoType::ExtProtoInfo EPI;
5802 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5803 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5804 EPI.NumExceptions = ExceptSpec.size();
5805 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005806 DeclarationName Name
5807 = Context.DeclarationNames.getCXXConstructorName(
5808 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005809 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005810 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005811 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005812 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005813 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005814 /*TInfo=*/0,
5815 /*isExplicit=*/false,
5816 /*isInline=*/true,
5817 /*isImplicitlyDeclared=*/true);
5818 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005819 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5820
Douglas Gregor22584312010-07-02 23:41:54 +00005821 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005822 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5823
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005824 // Add the parameter to the constructor.
5825 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5826 ClassDecl->getLocation(),
5827 /*IdentifierInfo=*/0,
5828 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005829 SC_None,
5830 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005831 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005832 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005833 PushOnScopeChains(CopyConstructor, S, false);
5834 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005835
5836 return CopyConstructor;
5837}
5838
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005839void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5840 CXXConstructorDecl *CopyConstructor,
5841 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005842 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005843 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005844 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005845 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005846
Anders Carlsson63010a72010-04-23 16:24:12 +00005847 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005848 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005849
Douglas Gregor39957dc2010-05-01 15:04:51 +00005850 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005851 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005852
Sean Huntcbb67482011-01-08 20:30:50 +00005853 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005854 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005855 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005856 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005857 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005858 } else {
5859 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5860 CopyConstructor->getLocation(),
5861 MultiStmtArg(*this, 0, 0),
5862 /*isStmtExpr=*/false)
5863 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005864 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005865
5866 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005867}
5868
John McCall60d7b3a2010-08-24 06:29:42 +00005869ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005870Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005871 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005872 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005873 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005874 unsigned ConstructKind,
5875 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005876 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005877
Douglas Gregor2f599792010-04-02 18:24:57 +00005878 // C++0x [class.copy]p34:
5879 // When certain criteria are met, an implementation is allowed to
5880 // omit the copy/move construction of a class object, even if the
5881 // copy/move constructor and/or destructor for the object have
5882 // side effects. [...]
5883 // - when a temporary class object that has not been bound to a
5884 // reference (12.2) would be copied/moved to a class object
5885 // with the same cv-unqualified type, the copy/move operation
5886 // can be omitted by constructing the temporary object
5887 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005888 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00005889 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005890 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005891 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005892 }
Mike Stump1eb44332009-09-09 15:08:12 +00005893
5894 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005895 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005896 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005897}
5898
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005899/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5900/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005901ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005902Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5903 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005904 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005905 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005906 unsigned ConstructKind,
5907 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005908 unsigned NumExprs = ExprArgs.size();
5909 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005910
Douglas Gregor7edfb692009-11-23 12:27:39 +00005911 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005912 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005913 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005914 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005915 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5916 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005917}
5918
Mike Stump1eb44332009-09-09 15:08:12 +00005919bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005920 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005921 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005922 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005923 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005924 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005925 move(Exprs), false, CXXConstructExpr::CK_Complete,
5926 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005927 if (TempResult.isInvalid())
5928 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005929
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005930 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005931 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005932 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005933 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005934 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005935
Anders Carlssonfe2de492009-08-25 05:18:00 +00005936 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005937}
5938
John McCall68c6c9a2010-02-02 09:10:11 +00005939void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5940 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005941 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005942 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005943 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005944 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005945 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005946 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005947 << VD->getDeclName()
5948 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005949
John McCallae792222010-09-18 05:25:11 +00005950 // TODO: this should be re-enabled for static locals by !CXAAtExit
5951 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005952 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005953 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005954}
5955
Mike Stump1eb44332009-09-09 15:08:12 +00005956/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005957/// ActOnDeclarator, when a C++ direct initializer is present.
5958/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005959void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005960 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005961 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005962 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005963 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005964
5965 // If there is no declaration, there was an error parsing it. Just ignore
5966 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005967 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005968 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005969
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005970 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5971 if (!VDecl) {
5972 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5973 RealDecl->setInvalidDecl();
5974 return;
5975 }
5976
Douglas Gregor83ddad32009-08-26 21:14:46 +00005977 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005978 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005979 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5980 //
5981 // Clients that want to distinguish between the two forms, can check for
5982 // direct initializer using VarDecl::hasCXXDirectInitializer().
5983 // A major benefit is that clients that don't particularly care about which
5984 // exactly form was it (like the CodeGen) can handle both cases without
5985 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005986
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005987 // C++ 8.5p11:
5988 // The form of initialization (using parentheses or '=') is generally
5989 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005990 // class type.
5991
Douglas Gregor4dffad62010-02-11 22:55:30 +00005992 if (!VDecl->getType()->isDependentType() &&
5993 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005994 diag::err_typecheck_decl_incomplete_type)) {
5995 VDecl->setInvalidDecl();
5996 return;
5997 }
5998
Douglas Gregor90f93822009-12-22 22:17:25 +00005999 // The variable can not have an abstract class type.
6000 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6001 diag::err_abstract_type_in_decl,
6002 AbstractVariableType))
6003 VDecl->setInvalidDecl();
6004
Sebastian Redl31310a22010-02-01 20:16:42 +00006005 const VarDecl *Def;
6006 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006007 Diag(VDecl->getLocation(), diag::err_redefinition)
6008 << VDecl->getDeclName();
6009 Diag(Def->getLocation(), diag::note_previous_definition);
6010 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006011 return;
6012 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006013
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006014 // C++ [class.static.data]p4
6015 // If a static data member is of const integral or const
6016 // enumeration type, its declaration in the class definition can
6017 // specify a constant-initializer which shall be an integral
6018 // constant expression (5.19). In that case, the member can appear
6019 // in integral constant expressions. The member shall still be
6020 // defined in a namespace scope if it is used in the program and the
6021 // namespace scope definition shall not contain an initializer.
6022 //
6023 // We already performed a redefinition check above, but for static
6024 // data members we also need to check whether there was an in-class
6025 // declaration with an initializer.
6026 const VarDecl* PrevInit = 0;
6027 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6028 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6029 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6030 return;
6031 }
6032
Douglas Gregora31040f2010-12-16 01:31:22 +00006033 bool IsDependent = false;
6034 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6035 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6036 VDecl->setInvalidDecl();
6037 return;
6038 }
6039
6040 if (Exprs.get()[I]->isTypeDependent())
6041 IsDependent = true;
6042 }
6043
Douglas Gregor4dffad62010-02-11 22:55:30 +00006044 // If either the declaration has a dependent type or if any of the
6045 // expressions is type-dependent, we represent the initialization
6046 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006047 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006048 // Let clients know that initialization was done with a direct initializer.
6049 VDecl->setCXXDirectInitializer(true);
6050
6051 // Store the initialization expressions as a ParenListExpr.
6052 unsigned NumExprs = Exprs.size();
6053 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6054 (Expr **)Exprs.release(),
6055 NumExprs, RParenLoc));
6056 return;
6057 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006058
6059 // Capture the variable that is being initialized and the style of
6060 // initialization.
6061 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6062
6063 // FIXME: Poor source location information.
6064 InitializationKind Kind
6065 = InitializationKind::CreateDirect(VDecl->getLocation(),
6066 LParenLoc, RParenLoc);
6067
6068 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006069 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006070 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006071 if (Result.isInvalid()) {
6072 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006073 return;
6074 }
John McCallb4eb64d2010-10-08 02:01:28 +00006075
6076 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006077
Douglas Gregor53c374f2010-12-07 00:41:46 +00006078 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006079 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006080 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006081
John McCall2998d6b2011-01-19 11:48:09 +00006082 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006083}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006084
Douglas Gregor39da0b82009-09-09 23:08:42 +00006085/// \brief Given a constructor and the set of arguments provided for the
6086/// constructor, convert the arguments and add any required default arguments
6087/// to form a proper call to this constructor.
6088///
6089/// \returns true if an error occurred, false otherwise.
6090bool
6091Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6092 MultiExprArg ArgsPtr,
6093 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006094 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006095 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6096 unsigned NumArgs = ArgsPtr.size();
6097 Expr **Args = (Expr **)ArgsPtr.get();
6098
6099 const FunctionProtoType *Proto
6100 = Constructor->getType()->getAs<FunctionProtoType>();
6101 assert(Proto && "Constructor without a prototype?");
6102 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006103
6104 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006105 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006106 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006107 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006108 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006109
6110 VariadicCallType CallType =
6111 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6112 llvm::SmallVector<Expr *, 8> AllArgs;
6113 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6114 Proto, 0, Args, NumArgs, AllArgs,
6115 CallType);
6116 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6117 ConvertedArgs.push_back(AllArgs[i]);
6118 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006119}
6120
Anders Carlsson20d45d22009-12-12 00:32:00 +00006121static inline bool
6122CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6123 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006124 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006125 if (isa<NamespaceDecl>(DC)) {
6126 return SemaRef.Diag(FnDecl->getLocation(),
6127 diag::err_operator_new_delete_declared_in_namespace)
6128 << FnDecl->getDeclName();
6129 }
6130
6131 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006132 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006133 return SemaRef.Diag(FnDecl->getLocation(),
6134 diag::err_operator_new_delete_declared_static)
6135 << FnDecl->getDeclName();
6136 }
6137
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006138 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006139}
6140
Anders Carlsson156c78e2009-12-13 17:53:43 +00006141static inline bool
6142CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6143 CanQualType ExpectedResultType,
6144 CanQualType ExpectedFirstParamType,
6145 unsigned DependentParamTypeDiag,
6146 unsigned InvalidParamTypeDiag) {
6147 QualType ResultType =
6148 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6149
6150 // Check that the result type is not dependent.
6151 if (ResultType->isDependentType())
6152 return SemaRef.Diag(FnDecl->getLocation(),
6153 diag::err_operator_new_delete_dependent_result_type)
6154 << FnDecl->getDeclName() << ExpectedResultType;
6155
6156 // Check that the result type is what we expect.
6157 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6158 return SemaRef.Diag(FnDecl->getLocation(),
6159 diag::err_operator_new_delete_invalid_result_type)
6160 << FnDecl->getDeclName() << ExpectedResultType;
6161
6162 // A function template must have at least 2 parameters.
6163 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6164 return SemaRef.Diag(FnDecl->getLocation(),
6165 diag::err_operator_new_delete_template_too_few_parameters)
6166 << FnDecl->getDeclName();
6167
6168 // The function decl must have at least 1 parameter.
6169 if (FnDecl->getNumParams() == 0)
6170 return SemaRef.Diag(FnDecl->getLocation(),
6171 diag::err_operator_new_delete_too_few_parameters)
6172 << FnDecl->getDeclName();
6173
6174 // Check the the first parameter type is not dependent.
6175 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6176 if (FirstParamType->isDependentType())
6177 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6178 << FnDecl->getDeclName() << ExpectedFirstParamType;
6179
6180 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006181 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006182 ExpectedFirstParamType)
6183 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6184 << FnDecl->getDeclName() << ExpectedFirstParamType;
6185
6186 return false;
6187}
6188
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006189static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006190CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006191 // C++ [basic.stc.dynamic.allocation]p1:
6192 // A program is ill-formed if an allocation function is declared in a
6193 // namespace scope other than global scope or declared static in global
6194 // scope.
6195 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6196 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006197
6198 CanQualType SizeTy =
6199 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6200
6201 // C++ [basic.stc.dynamic.allocation]p1:
6202 // The return type shall be void*. The first parameter shall have type
6203 // std::size_t.
6204 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6205 SizeTy,
6206 diag::err_operator_new_dependent_param_type,
6207 diag::err_operator_new_param_type))
6208 return true;
6209
6210 // C++ [basic.stc.dynamic.allocation]p1:
6211 // The first parameter shall not have an associated default argument.
6212 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006213 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006214 diag::err_operator_new_default_arg)
6215 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6216
6217 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006218}
6219
6220static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006221CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6222 // C++ [basic.stc.dynamic.deallocation]p1:
6223 // A program is ill-formed if deallocation functions are declared in a
6224 // namespace scope other than global scope or declared static in global
6225 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006226 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6227 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006228
6229 // C++ [basic.stc.dynamic.deallocation]p2:
6230 // Each deallocation function shall return void and its first parameter
6231 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006232 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6233 SemaRef.Context.VoidPtrTy,
6234 diag::err_operator_delete_dependent_param_type,
6235 diag::err_operator_delete_param_type))
6236 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006237
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006238 return false;
6239}
6240
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006241/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6242/// of this overloaded operator is well-formed. If so, returns false;
6243/// otherwise, emits appropriate diagnostics and returns true.
6244bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006245 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006246 "Expected an overloaded operator declaration");
6247
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006248 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6249
Mike Stump1eb44332009-09-09 15:08:12 +00006250 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006251 // The allocation and deallocation functions, operator new,
6252 // operator new[], operator delete and operator delete[], are
6253 // described completely in 3.7.3. The attributes and restrictions
6254 // found in the rest of this subclause do not apply to them unless
6255 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006256 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006257 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006258
Anders Carlssona3ccda52009-12-12 00:26:23 +00006259 if (Op == OO_New || Op == OO_Array_New)
6260 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006261
6262 // C++ [over.oper]p6:
6263 // An operator function shall either be a non-static member
6264 // function or be a non-member function and have at least one
6265 // parameter whose type is a class, a reference to a class, an
6266 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006267 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6268 if (MethodDecl->isStatic())
6269 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006270 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006271 } else {
6272 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006273 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6274 ParamEnd = FnDecl->param_end();
6275 Param != ParamEnd; ++Param) {
6276 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006277 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6278 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006279 ClassOrEnumParam = true;
6280 break;
6281 }
6282 }
6283
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006284 if (!ClassOrEnumParam)
6285 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006286 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006287 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006288 }
6289
6290 // C++ [over.oper]p8:
6291 // An operator function cannot have default arguments (8.3.6),
6292 // except where explicitly stated below.
6293 //
Mike Stump1eb44332009-09-09 15:08:12 +00006294 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006295 // (C++ [over.call]p1).
6296 if (Op != OO_Call) {
6297 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6298 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006299 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006300 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006301 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006302 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006303 }
6304 }
6305
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006306 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6307 { false, false, false }
6308#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6309 , { Unary, Binary, MemberOnly }
6310#include "clang/Basic/OperatorKinds.def"
6311 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006312
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006313 bool CanBeUnaryOperator = OperatorUses[Op][0];
6314 bool CanBeBinaryOperator = OperatorUses[Op][1];
6315 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006316
6317 // C++ [over.oper]p8:
6318 // [...] Operator functions cannot have more or fewer parameters
6319 // than the number required for the corresponding operator, as
6320 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006321 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006322 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006323 if (Op != OO_Call &&
6324 ((NumParams == 1 && !CanBeUnaryOperator) ||
6325 (NumParams == 2 && !CanBeBinaryOperator) ||
6326 (NumParams < 1) || (NumParams > 2))) {
6327 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006328 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006329 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006330 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006331 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006332 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006333 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006334 assert(CanBeBinaryOperator &&
6335 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006336 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006337 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006338
Chris Lattner416e46f2008-11-21 07:57:12 +00006339 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006340 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006341 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006342
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006343 // Overloaded operators other than operator() cannot be variadic.
6344 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006345 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006346 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006347 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006348 }
6349
6350 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006351 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6352 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006353 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006354 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006355 }
6356
6357 // C++ [over.inc]p1:
6358 // The user-defined function called operator++ implements the
6359 // prefix and postfix ++ operator. If this function is a member
6360 // function with no parameters, or a non-member function with one
6361 // parameter of class or enumeration type, it defines the prefix
6362 // increment operator ++ for objects of that type. If the function
6363 // is a member function with one parameter (which shall be of type
6364 // int) or a non-member function with two parameters (the second
6365 // of which shall be of type int), it defines the postfix
6366 // increment operator ++ for objects of that type.
6367 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6368 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6369 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006370 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006371 ParamIsInt = BT->getKind() == BuiltinType::Int;
6372
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006373 if (!ParamIsInt)
6374 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006375 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006376 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006377 }
6378
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006379 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006380}
Chris Lattner5a003a42008-12-17 07:09:26 +00006381
Sean Hunta6c058d2010-01-13 09:01:02 +00006382/// CheckLiteralOperatorDeclaration - Check whether the declaration
6383/// of this literal operator function is well-formed. If so, returns
6384/// false; otherwise, emits appropriate diagnostics and returns true.
6385bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6386 DeclContext *DC = FnDecl->getDeclContext();
6387 Decl::Kind Kind = DC->getDeclKind();
6388 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6389 Kind != Decl::LinkageSpec) {
6390 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6391 << FnDecl->getDeclName();
6392 return true;
6393 }
6394
6395 bool Valid = false;
6396
Sean Hunt216c2782010-04-07 23:11:06 +00006397 // template <char...> type operator "" name() is the only valid template
6398 // signature, and the only valid signature with no parameters.
6399 if (FnDecl->param_size() == 0) {
6400 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6401 // Must have only one template parameter
6402 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6403 if (Params->size() == 1) {
6404 NonTypeTemplateParmDecl *PmDecl =
6405 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006406
Sean Hunt216c2782010-04-07 23:11:06 +00006407 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006408 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6409 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6410 Valid = true;
6411 }
6412 }
6413 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006414 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006415 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6416
Sean Hunta6c058d2010-01-13 09:01:02 +00006417 QualType T = (*Param)->getType();
6418
Sean Hunt30019c02010-04-07 22:57:35 +00006419 // unsigned long long int, long double, and any character type are allowed
6420 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006421 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6422 Context.hasSameType(T, Context.LongDoubleTy) ||
6423 Context.hasSameType(T, Context.CharTy) ||
6424 Context.hasSameType(T, Context.WCharTy) ||
6425 Context.hasSameType(T, Context.Char16Ty) ||
6426 Context.hasSameType(T, Context.Char32Ty)) {
6427 if (++Param == FnDecl->param_end())
6428 Valid = true;
6429 goto FinishedParams;
6430 }
6431
Sean Hunt30019c02010-04-07 22:57:35 +00006432 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006433 const PointerType *PT = T->getAs<PointerType>();
6434 if (!PT)
6435 goto FinishedParams;
6436 T = PT->getPointeeType();
6437 if (!T.isConstQualified())
6438 goto FinishedParams;
6439 T = T.getUnqualifiedType();
6440
6441 // Move on to the second parameter;
6442 ++Param;
6443
6444 // If there is no second parameter, the first must be a const char *
6445 if (Param == FnDecl->param_end()) {
6446 if (Context.hasSameType(T, Context.CharTy))
6447 Valid = true;
6448 goto FinishedParams;
6449 }
6450
6451 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6452 // are allowed as the first parameter to a two-parameter function
6453 if (!(Context.hasSameType(T, Context.CharTy) ||
6454 Context.hasSameType(T, Context.WCharTy) ||
6455 Context.hasSameType(T, Context.Char16Ty) ||
6456 Context.hasSameType(T, Context.Char32Ty)))
6457 goto FinishedParams;
6458
6459 // The second and final parameter must be an std::size_t
6460 T = (*Param)->getType().getUnqualifiedType();
6461 if (Context.hasSameType(T, Context.getSizeType()) &&
6462 ++Param == FnDecl->param_end())
6463 Valid = true;
6464 }
6465
6466 // FIXME: This diagnostic is absolutely terrible.
6467FinishedParams:
6468 if (!Valid) {
6469 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6470 << FnDecl->getDeclName();
6471 return true;
6472 }
6473
6474 return false;
6475}
6476
Douglas Gregor074149e2009-01-05 19:45:36 +00006477/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6478/// linkage specification, including the language and (if present)
6479/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6480/// the location of the language string literal, which is provided
6481/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6482/// the '{' brace. Otherwise, this linkage specification does not
6483/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006484Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6485 SourceLocation LangLoc,
6486 llvm::StringRef Lang,
6487 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006488 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006489 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006490 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006491 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006492 Language = LinkageSpecDecl::lang_cxx;
6493 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006494 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006495 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006496 }
Mike Stump1eb44332009-09-09 15:08:12 +00006497
Chris Lattnercc98eac2008-12-17 07:13:27 +00006498 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006499
Douglas Gregor074149e2009-01-05 19:45:36 +00006500 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006501 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006502 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006503 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006504 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006505 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006506}
6507
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006508/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006509/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6510/// valid, it's the position of the closing '}' brace in a linkage
6511/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006512Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6513 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006514 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006515 if (LinkageSpec)
6516 PopDeclContext();
6517 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006518}
6519
Douglas Gregord308e622009-05-18 20:51:54 +00006520/// \brief Perform semantic analysis for the variable declaration that
6521/// occurs within a C++ catch clause, returning the newly-created
6522/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006523VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006524 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006525 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006526 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006527 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006528 QualType ExDeclType = TInfo->getType();
6529
Sebastian Redl4b07b292008-12-22 19:15:10 +00006530 // Arrays and functions decay.
6531 if (ExDeclType->isArrayType())
6532 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6533 else if (ExDeclType->isFunctionType())
6534 ExDeclType = Context.getPointerType(ExDeclType);
6535
6536 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6537 // The exception-declaration shall not denote a pointer or reference to an
6538 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006539 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006540 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006541 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006542 Invalid = true;
6543 }
Douglas Gregord308e622009-05-18 20:51:54 +00006544
Douglas Gregora2762912010-03-08 01:47:36 +00006545 // GCC allows catching pointers and references to incomplete types
6546 // as an extension; so do we, but we warn by default.
6547
Sebastian Redl4b07b292008-12-22 19:15:10 +00006548 QualType BaseType = ExDeclType;
6549 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006550 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006551 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006552 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006553 BaseType = Ptr->getPointeeType();
6554 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006555 DK = diag::ext_catch_incomplete_ptr;
6556 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006557 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006558 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006559 BaseType = Ref->getPointeeType();
6560 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006561 DK = diag::ext_catch_incomplete_ref;
6562 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006563 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006564 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006565 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6566 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006567 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006568
Mike Stump1eb44332009-09-09 15:08:12 +00006569 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006570 RequireNonAbstractType(Loc, ExDeclType,
6571 diag::err_abstract_type_in_decl,
6572 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006573 Invalid = true;
6574
John McCall5a180392010-07-24 00:37:23 +00006575 // Only the non-fragile NeXT runtime currently supports C++ catches
6576 // of ObjC types, and no runtime supports catching ObjC types by value.
6577 if (!Invalid && getLangOptions().ObjC1) {
6578 QualType T = ExDeclType;
6579 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6580 T = RT->getPointeeType();
6581
6582 if (T->isObjCObjectType()) {
6583 Diag(Loc, diag::err_objc_object_catch);
6584 Invalid = true;
6585 } else if (T->isObjCObjectPointerType()) {
6586 if (!getLangOptions().NeXTRuntime) {
6587 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6588 Invalid = true;
6589 } else if (!getLangOptions().ObjCNonFragileABI) {
6590 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6591 Invalid = true;
6592 }
6593 }
6594 }
6595
Mike Stump1eb44332009-09-09 15:08:12 +00006596 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006597 Name, ExDeclType, TInfo, SC_None,
6598 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006599 ExDecl->setExceptionVariable(true);
6600
Douglas Gregor6d182892010-03-05 23:38:39 +00006601 if (!Invalid) {
6602 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6603 // C++ [except.handle]p16:
6604 // The object declared in an exception-declaration or, if the
6605 // exception-declaration does not specify a name, a temporary (12.2) is
6606 // copy-initialized (8.5) from the exception object. [...]
6607 // The object is destroyed when the handler exits, after the destruction
6608 // of any automatic objects initialized within the handler.
6609 //
6610 // We just pretend to initialize the object with itself, then make sure
6611 // it can be destroyed later.
6612 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6613 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006614 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006615 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6616 SourceLocation());
6617 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006618 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006619 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006620 if (Result.isInvalid())
6621 Invalid = true;
6622 else
6623 FinalizeVarWithDestructor(ExDecl, RecordTy);
6624 }
6625 }
6626
Douglas Gregord308e622009-05-18 20:51:54 +00006627 if (Invalid)
6628 ExDecl->setInvalidDecl();
6629
6630 return ExDecl;
6631}
6632
6633/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6634/// handler.
John McCalld226f652010-08-21 09:40:31 +00006635Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006636 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006637 bool Invalid = D.isInvalidType();
6638
6639 // Check for unexpanded parameter packs.
6640 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6641 UPPC_ExceptionType)) {
6642 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6643 D.getIdentifierLoc());
6644 Invalid = true;
6645 }
6646
Sebastian Redl4b07b292008-12-22 19:15:10 +00006647 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006648 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006649 LookupOrdinaryName,
6650 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006651 // The scope should be freshly made just for us. There is just no way
6652 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006653 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006654 if (PrevDecl->isTemplateParameter()) {
6655 // Maybe we will complain about the shadowed template parameter.
6656 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006657 }
6658 }
6659
Chris Lattnereaaebc72009-04-25 08:06:05 +00006660 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006661 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6662 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006663 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006664 }
6665
Douglas Gregor83cb9422010-09-09 17:09:21 +00006666 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006667 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006668 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006669
Chris Lattnereaaebc72009-04-25 08:06:05 +00006670 if (Invalid)
6671 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006672
Sebastian Redl4b07b292008-12-22 19:15:10 +00006673 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006674 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006675 PushOnScopeChains(ExDecl, S);
6676 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006677 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006678
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006679 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006680 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006681}
Anders Carlssonfb311762009-03-14 00:25:26 +00006682
John McCalld226f652010-08-21 09:40:31 +00006683Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006684 Expr *AssertExpr,
6685 Expr *AssertMessageExpr_) {
6686 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006687
Anders Carlssonc3082412009-03-14 00:33:21 +00006688 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6689 llvm::APSInt Value(32);
6690 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6691 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6692 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006693 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006694 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006695
Anders Carlssonc3082412009-03-14 00:33:21 +00006696 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006697 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006698 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006699 }
6700 }
Mike Stump1eb44332009-09-09 15:08:12 +00006701
Douglas Gregor399ad972010-12-15 23:55:21 +00006702 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6703 return 0;
6704
Mike Stump1eb44332009-09-09 15:08:12 +00006705 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006706 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006707
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006708 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006709 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006710}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006711
Douglas Gregor1d869352010-04-07 16:53:43 +00006712/// \brief Perform semantic analysis of the given friend type declaration.
6713///
6714/// \returns A friend declaration that.
6715FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6716 TypeSourceInfo *TSInfo) {
6717 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6718
6719 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006720 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006721
Douglas Gregor06245bf2010-04-07 17:57:12 +00006722 if (!getLangOptions().CPlusPlus0x) {
6723 // C++03 [class.friend]p2:
6724 // An elaborated-type-specifier shall be used in a friend declaration
6725 // for a class.*
6726 //
6727 // * The class-key of the elaborated-type-specifier is required.
6728 if (!ActiveTemplateInstantiations.empty()) {
6729 // Do not complain about the form of friend template types during
6730 // template instantiation; we will already have complained when the
6731 // template was declared.
6732 } else if (!T->isElaboratedTypeSpecifier()) {
6733 // If we evaluated the type to a record type, suggest putting
6734 // a tag in front.
6735 if (const RecordType *RT = T->getAs<RecordType>()) {
6736 RecordDecl *RD = RT->getDecl();
6737
6738 std::string InsertionText = std::string(" ") + RD->getKindName();
6739
6740 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6741 << (unsigned) RD->getTagKind()
6742 << T
6743 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6744 InsertionText);
6745 } else {
6746 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6747 << T
6748 << SourceRange(FriendLoc, TypeRange.getEnd());
6749 }
6750 } else if (T->getAs<EnumType>()) {
6751 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006752 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006753 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006754 }
6755 }
6756
Douglas Gregor06245bf2010-04-07 17:57:12 +00006757 // C++0x [class.friend]p3:
6758 // If the type specifier in a friend declaration designates a (possibly
6759 // cv-qualified) class type, that class is declared as a friend; otherwise,
6760 // the friend declaration is ignored.
6761
6762 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6763 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006764
6765 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6766}
6767
John McCall9a34edb2010-10-19 01:40:49 +00006768/// Handle a friend tag declaration where the scope specifier was
6769/// templated.
6770Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6771 unsigned TagSpec, SourceLocation TagLoc,
6772 CXXScopeSpec &SS,
6773 IdentifierInfo *Name, SourceLocation NameLoc,
6774 AttributeList *Attr,
6775 MultiTemplateParamsArg TempParamLists) {
6776 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6777
6778 bool isExplicitSpecialization = false;
6779 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6780 bool Invalid = false;
6781
6782 if (TemplateParameterList *TemplateParams
6783 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6784 TempParamLists.get(),
6785 TempParamLists.size(),
6786 /*friend*/ true,
6787 isExplicitSpecialization,
6788 Invalid)) {
6789 --NumMatchedTemplateParamLists;
6790
6791 if (TemplateParams->size() > 0) {
6792 // This is a declaration of a class template.
6793 if (Invalid)
6794 return 0;
6795
6796 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6797 SS, Name, NameLoc, Attr,
6798 TemplateParams, AS_public).take();
6799 } else {
6800 // The "template<>" header is extraneous.
6801 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6802 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6803 isExplicitSpecialization = true;
6804 }
6805 }
6806
6807 if (Invalid) return 0;
6808
6809 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6810
6811 bool isAllExplicitSpecializations = true;
6812 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6813 if (TempParamLists.get()[I]->size()) {
6814 isAllExplicitSpecializations = false;
6815 break;
6816 }
6817 }
6818
6819 // FIXME: don't ignore attributes.
6820
6821 // If it's explicit specializations all the way down, just forget
6822 // about the template header and build an appropriate non-templated
6823 // friend. TODO: for source fidelity, remember the headers.
6824 if (isAllExplicitSpecializations) {
6825 ElaboratedTypeKeyword Keyword
6826 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6827 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6828 TagLoc, SS.getRange(), NameLoc);
6829 if (T.isNull())
6830 return 0;
6831
6832 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6833 if (isa<DependentNameType>(T)) {
6834 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6835 TL.setKeywordLoc(TagLoc);
6836 TL.setQualifierRange(SS.getRange());
6837 TL.setNameLoc(NameLoc);
6838 } else {
6839 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6840 TL.setKeywordLoc(TagLoc);
6841 TL.setQualifierRange(SS.getRange());
6842 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6843 }
6844
6845 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6846 TSI, FriendLoc);
6847 Friend->setAccess(AS_public);
6848 CurContext->addDecl(Friend);
6849 return Friend;
6850 }
6851
6852 // Handle the case of a templated-scope friend class. e.g.
6853 // template <class T> class A<T>::B;
6854 // FIXME: we don't support these right now.
6855 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6856 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6857 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6858 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6859 TL.setKeywordLoc(TagLoc);
6860 TL.setQualifierRange(SS.getRange());
6861 TL.setNameLoc(NameLoc);
6862
6863 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6864 TSI, FriendLoc);
6865 Friend->setAccess(AS_public);
6866 Friend->setUnsupportedFriend(true);
6867 CurContext->addDecl(Friend);
6868 return Friend;
6869}
6870
6871
John McCalldd4a3b02009-09-16 22:47:08 +00006872/// Handle a friend type declaration. This works in tandem with
6873/// ActOnTag.
6874///
6875/// Notes on friend class templates:
6876///
6877/// We generally treat friend class declarations as if they were
6878/// declaring a class. So, for example, the elaborated type specifier
6879/// in a friend declaration is required to obey the restrictions of a
6880/// class-head (i.e. no typedefs in the scope chain), template
6881/// parameters are required to match up with simple template-ids, &c.
6882/// However, unlike when declaring a template specialization, it's
6883/// okay to refer to a template specialization without an empty
6884/// template parameter declaration, e.g.
6885/// friend class A<T>::B<unsigned>;
6886/// We permit this as a special case; if there are any template
6887/// parameters present at all, require proper matching, i.e.
6888/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006889Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006890 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006891 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006892
6893 assert(DS.isFriendSpecified());
6894 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6895
John McCalldd4a3b02009-09-16 22:47:08 +00006896 // Try to convert the decl specifier to a type. This works for
6897 // friend templates because ActOnTag never produces a ClassTemplateDecl
6898 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006899 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006900 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6901 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006902 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006903 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006904
Douglas Gregor6ccab972010-12-16 01:14:37 +00006905 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6906 return 0;
6907
John McCalldd4a3b02009-09-16 22:47:08 +00006908 // This is definitely an error in C++98. It's probably meant to
6909 // be forbidden in C++0x, too, but the specification is just
6910 // poorly written.
6911 //
6912 // The problem is with declarations like the following:
6913 // template <T> friend A<T>::foo;
6914 // where deciding whether a class C is a friend or not now hinges
6915 // on whether there exists an instantiation of A that causes
6916 // 'foo' to equal C. There are restrictions on class-heads
6917 // (which we declare (by fiat) elaborated friend declarations to
6918 // be) that makes this tractable.
6919 //
6920 // FIXME: handle "template <> friend class A<T>;", which
6921 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006922 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006923 Diag(Loc, diag::err_tagless_friend_type_template)
6924 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006925 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006926 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006927
John McCall02cace72009-08-28 07:59:38 +00006928 // C++98 [class.friend]p1: A friend of a class is a function
6929 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006930 // This is fixed in DR77, which just barely didn't make the C++03
6931 // deadline. It's also a very silly restriction that seriously
6932 // affects inner classes and which nobody else seems to implement;
6933 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006934 //
6935 // But note that we could warn about it: it's always useless to
6936 // friend one of your own members (it's not, however, worthless to
6937 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006938
John McCalldd4a3b02009-09-16 22:47:08 +00006939 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006940 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006941 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006942 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006943 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006944 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006945 DS.getFriendSpecLoc());
6946 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006947 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6948
6949 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006950 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006951
John McCalldd4a3b02009-09-16 22:47:08 +00006952 D->setAccess(AS_public);
6953 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006954
John McCalld226f652010-08-21 09:40:31 +00006955 return D;
John McCall02cace72009-08-28 07:59:38 +00006956}
6957
John McCall337ec3d2010-10-12 23:13:28 +00006958Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6959 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006960 const DeclSpec &DS = D.getDeclSpec();
6961
6962 assert(DS.isFriendSpecified());
6963 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6964
6965 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006966 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6967 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006968
6969 // C++ [class.friend]p1
6970 // A friend of a class is a function or class....
6971 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006972 // It *doesn't* see through dependent types, which is correct
6973 // according to [temp.arg.type]p3:
6974 // If a declaration acquires a function type through a
6975 // type dependent on a template-parameter and this causes
6976 // a declaration that does not use the syntactic form of a
6977 // function declarator to have a function type, the program
6978 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006979 if (!T->isFunctionType()) {
6980 Diag(Loc, diag::err_unexpected_friend);
6981
6982 // It might be worthwhile to try to recover by creating an
6983 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006984 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006985 }
6986
6987 // C++ [namespace.memdef]p3
6988 // - If a friend declaration in a non-local class first declares a
6989 // class or function, the friend class or function is a member
6990 // of the innermost enclosing namespace.
6991 // - The name of the friend is not found by simple name lookup
6992 // until a matching declaration is provided in that namespace
6993 // scope (either before or after the class declaration granting
6994 // friendship).
6995 // - If a friend function is called, its name may be found by the
6996 // name lookup that considers functions from namespaces and
6997 // classes associated with the types of the function arguments.
6998 // - When looking for a prior declaration of a class or a function
6999 // declared as a friend, scopes outside the innermost enclosing
7000 // namespace scope are not considered.
7001
John McCall337ec3d2010-10-12 23:13:28 +00007002 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007003 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7004 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007005 assert(Name);
7006
Douglas Gregor6ccab972010-12-16 01:14:37 +00007007 // Check for unexpanded parameter packs.
7008 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7009 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7010 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7011 return 0;
7012
John McCall67d1a672009-08-06 02:15:43 +00007013 // The context we found the declaration in, or in which we should
7014 // create the declaration.
7015 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007016 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007017 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007018 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007019
John McCall337ec3d2010-10-12 23:13:28 +00007020 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007021
John McCall337ec3d2010-10-12 23:13:28 +00007022 // There are four cases here.
7023 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007024 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007025 // there as appropriate.
7026 // Recover from invalid scope qualifiers as if they just weren't there.
7027 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007028 // C++0x [namespace.memdef]p3:
7029 // If the name in a friend declaration is neither qualified nor
7030 // a template-id and the declaration is a function or an
7031 // elaborated-type-specifier, the lookup to determine whether
7032 // the entity has been previously declared shall not consider
7033 // any scopes outside the innermost enclosing namespace.
7034 // C++0x [class.friend]p11:
7035 // If a friend declaration appears in a local class and the name
7036 // specified is an unqualified name, a prior declaration is
7037 // looked up without considering scopes that are outside the
7038 // innermost enclosing non-class scope. For a friend function
7039 // declaration, if there is no prior declaration, the program is
7040 // ill-formed.
7041 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007042 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007043
John McCall29ae6e52010-10-13 05:45:15 +00007044 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007045 DC = CurContext;
7046 while (true) {
7047 // Skip class contexts. If someone can cite chapter and verse
7048 // for this behavior, that would be nice --- it's what GCC and
7049 // EDG do, and it seems like a reasonable intent, but the spec
7050 // really only says that checks for unqualified existing
7051 // declarations should stop at the nearest enclosing namespace,
7052 // not that they should only consider the nearest enclosing
7053 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007054 while (DC->isRecord())
7055 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007056
John McCall68263142009-11-18 22:49:29 +00007057 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007058
7059 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007060 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007061 break;
John McCall29ae6e52010-10-13 05:45:15 +00007062
John McCall8a407372010-10-14 22:22:28 +00007063 if (isTemplateId) {
7064 if (isa<TranslationUnitDecl>(DC)) break;
7065 } else {
7066 if (DC->isFileContext()) break;
7067 }
John McCall67d1a672009-08-06 02:15:43 +00007068 DC = DC->getParent();
7069 }
7070
7071 // C++ [class.friend]p1: A friend of a class is a function or
7072 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007073 // C++0x changes this for both friend types and functions.
7074 // Most C++ 98 compilers do seem to give an error here, so
7075 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007076 if (!Previous.empty() && DC->Equals(CurContext)
7077 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007078 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007079
John McCall380aaa42010-10-13 06:22:15 +00007080 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007081
John McCall337ec3d2010-10-12 23:13:28 +00007082 // - There's a non-dependent scope specifier, in which case we
7083 // compute it and do a previous lookup there for a function
7084 // or function template.
7085 } else if (!SS.getScopeRep()->isDependent()) {
7086 DC = computeDeclContext(SS);
7087 if (!DC) return 0;
7088
7089 if (RequireCompleteDeclContext(SS, DC)) return 0;
7090
7091 LookupQualifiedName(Previous, DC);
7092
7093 // Ignore things found implicitly in the wrong scope.
7094 // TODO: better diagnostics for this case. Suggesting the right
7095 // qualified scope would be nice...
7096 LookupResult::Filter F = Previous.makeFilter();
7097 while (F.hasNext()) {
7098 NamedDecl *D = F.next();
7099 if (!DC->InEnclosingNamespaceSetOf(
7100 D->getDeclContext()->getRedeclContext()))
7101 F.erase();
7102 }
7103 F.done();
7104
7105 if (Previous.empty()) {
7106 D.setInvalidType();
7107 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7108 return 0;
7109 }
7110
7111 // C++ [class.friend]p1: A friend of a class is a function or
7112 // class that is not a member of the class . . .
7113 if (DC->Equals(CurContext))
7114 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7115
7116 // - There's a scope specifier that does not match any template
7117 // parameter lists, in which case we use some arbitrary context,
7118 // create a method or method template, and wait for instantiation.
7119 // - There's a scope specifier that does match some template
7120 // parameter lists, which we don't handle right now.
7121 } else {
7122 DC = CurContext;
7123 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007124 }
7125
John McCall29ae6e52010-10-13 05:45:15 +00007126 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007127 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007128 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7129 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7130 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007131 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007132 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7133 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007134 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007135 }
John McCall67d1a672009-08-06 02:15:43 +00007136 }
7137
Douglas Gregor182ddf02009-09-28 00:08:27 +00007138 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007139 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007140 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007141 IsDefinition,
7142 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007143 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007144
Douglas Gregor182ddf02009-09-28 00:08:27 +00007145 assert(ND->getDeclContext() == DC);
7146 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007147
John McCallab88d972009-08-31 22:39:49 +00007148 // Add the function declaration to the appropriate lookup tables,
7149 // adjusting the redeclarations list as necessary. We don't
7150 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007151 //
John McCallab88d972009-08-31 22:39:49 +00007152 // Also update the scope-based lookup if the target context's
7153 // lookup context is in lexical scope.
7154 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007155 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007156 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007157 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007158 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007159 }
John McCall02cace72009-08-28 07:59:38 +00007160
7161 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007162 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007163 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007164 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007165 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007166
John McCall337ec3d2010-10-12 23:13:28 +00007167 if (ND->isInvalidDecl())
7168 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007169 else {
7170 FunctionDecl *FD;
7171 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7172 FD = FTD->getTemplatedDecl();
7173 else
7174 FD = cast<FunctionDecl>(ND);
7175
7176 // Mark templated-scope function declarations as unsupported.
7177 if (FD->getNumTemplateParameterLists())
7178 FrD->setUnsupportedFriend(true);
7179 }
John McCall337ec3d2010-10-12 23:13:28 +00007180
John McCalld226f652010-08-21 09:40:31 +00007181 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007182}
7183
John McCalld226f652010-08-21 09:40:31 +00007184void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7185 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007186
Sebastian Redl50de12f2009-03-24 22:27:57 +00007187 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7188 if (!Fn) {
7189 Diag(DelLoc, diag::err_deleted_non_function);
7190 return;
7191 }
7192 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7193 Diag(DelLoc, diag::err_deleted_decl_not_first);
7194 Diag(Prev->getLocation(), diag::note_previous_declaration);
7195 // If the declaration wasn't the first, we delete the function anyway for
7196 // recovery.
7197 }
7198 Fn->setDeleted();
7199}
Sebastian Redl13e88542009-04-27 21:33:24 +00007200
7201static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
7202 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
7203 ++CI) {
7204 Stmt *SubStmt = *CI;
7205 if (!SubStmt)
7206 continue;
7207 if (isa<ReturnStmt>(SubStmt))
7208 Self.Diag(SubStmt->getSourceRange().getBegin(),
7209 diag::err_return_in_constructor_handler);
7210 if (!isa<Expr>(SubStmt))
7211 SearchForReturnInStmt(Self, SubStmt);
7212 }
7213}
7214
7215void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7216 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7217 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7218 SearchForReturnInStmt(*this, Handler);
7219 }
7220}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007221
Mike Stump1eb44332009-09-09 15:08:12 +00007222bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007223 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007224 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7225 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007226
Chandler Carruth73857792010-02-15 11:53:20 +00007227 if (Context.hasSameType(NewTy, OldTy) ||
7228 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007230
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007231 // Check if the return types are covariant
7232 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007233
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007234 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007235 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7236 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007237 NewClassTy = NewPT->getPointeeType();
7238 OldClassTy = OldPT->getPointeeType();
7239 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007240 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7241 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7242 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7243 NewClassTy = NewRT->getPointeeType();
7244 OldClassTy = OldRT->getPointeeType();
7245 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007246 }
7247 }
Mike Stump1eb44332009-09-09 15:08:12 +00007248
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007249 // The return types aren't either both pointers or references to a class type.
7250 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007251 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007252 diag::err_different_return_type_for_overriding_virtual_function)
7253 << New->getDeclName() << NewTy << OldTy;
7254 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007255
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007256 return true;
7257 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007258
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007259 // C++ [class.virtual]p6:
7260 // If the return type of D::f differs from the return type of B::f, the
7261 // class type in the return type of D::f shall be complete at the point of
7262 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007263 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7264 if (!RT->isBeingDefined() &&
7265 RequireCompleteType(New->getLocation(), NewClassTy,
7266 PDiag(diag::err_covariant_return_incomplete)
7267 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007268 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007269 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007270
Douglas Gregora4923eb2009-11-16 21:35:15 +00007271 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007272 // Check if the new class derives from the old class.
7273 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7274 Diag(New->getLocation(),
7275 diag::err_covariant_return_not_derived)
7276 << New->getDeclName() << NewTy << OldTy;
7277 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7278 return true;
7279 }
Mike Stump1eb44332009-09-09 15:08:12 +00007280
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007281 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007282 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007283 diag::err_covariant_return_inaccessible_base,
7284 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7285 // FIXME: Should this point to the return type?
7286 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007287 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7288 return true;
7289 }
7290 }
Mike Stump1eb44332009-09-09 15:08:12 +00007291
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007292 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007293 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007294 Diag(New->getLocation(),
7295 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007296 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007297 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7298 return true;
7299 };
Mike Stump1eb44332009-09-09 15:08:12 +00007300
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007301
7302 // The new class type must have the same or less qualifiers as the old type.
7303 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7304 Diag(New->getLocation(),
7305 diag::err_covariant_return_type_class_type_more_qualified)
7306 << New->getDeclName() << NewTy << OldTy;
7307 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7308 return true;
7309 };
Mike Stump1eb44332009-09-09 15:08:12 +00007310
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007311 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007312}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007313
Douglas Gregor4ba31362009-12-01 17:24:26 +00007314/// \brief Mark the given method pure.
7315///
7316/// \param Method the method to be marked pure.
7317///
7318/// \param InitRange the source range that covers the "0" initializer.
7319bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7320 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7321 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007322 return false;
7323 }
7324
7325 if (!Method->isInvalidDecl())
7326 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7327 << Method->getDeclName() << InitRange;
7328 return true;
7329}
7330
John McCall731ad842009-12-19 09:28:58 +00007331/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7332/// an initializer for the out-of-line declaration 'Dcl'. The scope
7333/// is a fresh scope pushed for just this purpose.
7334///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007335/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7336/// static data member of class X, names should be looked up in the scope of
7337/// class X.
John McCalld226f652010-08-21 09:40:31 +00007338void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007339 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007340 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007341
John McCall731ad842009-12-19 09:28:58 +00007342 // We should only get called for declarations with scope specifiers, like:
7343 // int foo::bar;
7344 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007345 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007346}
7347
7348/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007349/// initializer for the out-of-line declaration 'D'.
7350void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007351 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007352 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007353
John McCall731ad842009-12-19 09:28:58 +00007354 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007355 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007356}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007357
7358/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7359/// C++ if/switch/while/for statement.
7360/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007361DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007362 // C++ 6.4p2:
7363 // The declarator shall not specify a function or an array.
7364 // The type-specifier-seq shall not contain typedef and shall not declare a
7365 // new class or enumeration.
7366 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7367 "Parser allowed 'typedef' as storage class of condition decl.");
7368
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007369 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007370 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7371 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007372
7373 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7374 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7375 // would be created and CXXConditionDeclExpr wants a VarDecl.
7376 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7377 << D.getSourceRange();
7378 return DeclResult();
7379 } else if (OwnedTag && OwnedTag->isDefinition()) {
7380 // The type-specifier-seq shall not declare a new class or enumeration.
7381 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7382 }
7383
John McCalld226f652010-08-21 09:40:31 +00007384 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007385 if (!Dcl)
7386 return DeclResult();
7387
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007388 return Dcl;
7389}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007390
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007391void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7392 bool DefinitionRequired) {
7393 // Ignore any vtable uses in unevaluated operands or for classes that do
7394 // not have a vtable.
7395 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7396 CurContext->isDependentContext() ||
7397 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007398 return;
7399
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007400 // Try to insert this class into the map.
7401 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7402 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7403 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7404 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007405 // If we already had an entry, check to see if we are promoting this vtable
7406 // to required a definition. If so, we need to reappend to the VTableUses
7407 // list, since we may have already processed the first entry.
7408 if (DefinitionRequired && !Pos.first->second) {
7409 Pos.first->second = true;
7410 } else {
7411 // Otherwise, we can early exit.
7412 return;
7413 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007414 }
7415
7416 // Local classes need to have their virtual members marked
7417 // immediately. For all other classes, we mark their virtual members
7418 // at the end of the translation unit.
7419 if (Class->isLocalClass())
7420 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007421 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007422 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007423}
7424
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007425bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007426 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007427 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007428
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007429 // Note: The VTableUses vector could grow as a result of marking
7430 // the members of a class as "used", so we check the size each
7431 // time through the loop and prefer indices (with are stable) to
7432 // iterators (which are not).
7433 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007434 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007435 if (!Class)
7436 continue;
7437
7438 SourceLocation Loc = VTableUses[I].second;
7439
7440 // If this class has a key function, but that key function is
7441 // defined in another translation unit, we don't need to emit the
7442 // vtable even though we're using it.
7443 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007444 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007445 switch (KeyFunction->getTemplateSpecializationKind()) {
7446 case TSK_Undeclared:
7447 case TSK_ExplicitSpecialization:
7448 case TSK_ExplicitInstantiationDeclaration:
7449 // The key function is in another translation unit.
7450 continue;
7451
7452 case TSK_ExplicitInstantiationDefinition:
7453 case TSK_ImplicitInstantiation:
7454 // We will be instantiating the key function.
7455 break;
7456 }
7457 } else if (!KeyFunction) {
7458 // If we have a class with no key function that is the subject
7459 // of an explicit instantiation declaration, suppress the
7460 // vtable; it will live with the explicit instantiation
7461 // definition.
7462 bool IsExplicitInstantiationDeclaration
7463 = Class->getTemplateSpecializationKind()
7464 == TSK_ExplicitInstantiationDeclaration;
7465 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7466 REnd = Class->redecls_end();
7467 R != REnd; ++R) {
7468 TemplateSpecializationKind TSK
7469 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7470 if (TSK == TSK_ExplicitInstantiationDeclaration)
7471 IsExplicitInstantiationDeclaration = true;
7472 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7473 IsExplicitInstantiationDeclaration = false;
7474 break;
7475 }
7476 }
7477
7478 if (IsExplicitInstantiationDeclaration)
7479 continue;
7480 }
7481
7482 // Mark all of the virtual members of this class as referenced, so
7483 // that we can build a vtable. Then, tell the AST consumer that a
7484 // vtable for this class is required.
7485 MarkVirtualMembersReferenced(Loc, Class);
7486 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7487 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7488
7489 // Optionally warn if we're emitting a weak vtable.
7490 if (Class->getLinkage() == ExternalLinkage &&
7491 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007492 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007493 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7494 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007495 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007496 VTableUses.clear();
7497
Anders Carlssond6a637f2009-12-07 08:24:59 +00007498 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007499}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007500
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007501void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7502 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007503 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7504 e = RD->method_end(); i != e; ++i) {
7505 CXXMethodDecl *MD = *i;
7506
7507 // C++ [basic.def.odr]p2:
7508 // [...] A virtual member function is used if it is not pure. [...]
7509 if (MD->isVirtual() && !MD->isPure())
7510 MarkDeclarationReferenced(Loc, MD);
7511 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007512
7513 // Only classes that have virtual bases need a VTT.
7514 if (RD->getNumVBases() == 0)
7515 return;
7516
7517 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7518 e = RD->bases_end(); i != e; ++i) {
7519 const CXXRecordDecl *Base =
7520 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007521 if (Base->getNumVBases() == 0)
7522 continue;
7523 MarkVirtualMembersReferenced(Loc, Base);
7524 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007525}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007526
7527/// SetIvarInitializers - This routine builds initialization ASTs for the
7528/// Objective-C implementation whose ivars need be initialized.
7529void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7530 if (!getLangOptions().CPlusPlus)
7531 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007532 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007533 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7534 CollectIvarsToConstructOrDestruct(OID, ivars);
7535 if (ivars.empty())
7536 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007537 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007538 for (unsigned i = 0; i < ivars.size(); i++) {
7539 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007540 if (Field->isInvalidDecl())
7541 continue;
7542
Sean Huntcbb67482011-01-08 20:30:50 +00007543 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007544 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7545 InitializationKind InitKind =
7546 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7547
7548 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007549 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007550 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007551 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007552 // Note, MemberInit could actually come back empty if no initialization
7553 // is required (e.g., because it would call a trivial default constructor)
7554 if (!MemberInit.get() || MemberInit.isInvalid())
7555 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007556
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007557 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007558 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7559 SourceLocation(),
7560 MemberInit.takeAs<Expr>(),
7561 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007562 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007563
7564 // Be sure that the destructor is accessible and is marked as referenced.
7565 if (const RecordType *RecordTy
7566 = Context.getBaseElementType(Field->getType())
7567 ->getAs<RecordType>()) {
7568 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007569 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007570 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7571 CheckDestructorAccess(Field->getLocation(), Destructor,
7572 PDiag(diag::err_access_dtor_ivar)
7573 << Context.getBaseElementType(Field->getType()));
7574 }
7575 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007576 }
7577 ObjCImplementation->setIvarInitializers(Context,
7578 AllToInit.data(), AllToInit.size());
7579 }
7580}