blob: e7bd7d5e87071bbc3f18a303519be41f8dff0e1e [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
Sean Huntbbd37c62009-11-21 08:43:09 +0000524 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
525 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
526 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531
John McCall572fc622010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000539}
540
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000541/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
542/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000546BaseResult
John McCalld226f652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregor40808ce2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky56062202010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000561
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000566
Douglas Gregor2943aed2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000573}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000574
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575/// \brief Performs the actual work of attaching the given base class
576/// specifiers to a C++ class.
577bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
578 unsigned NumBases) {
579 if (NumBases == 0)
580 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000581
582 // Used to keep track of which base types we have already seen, so
583 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000595 if (!Class->hasObjectMember()) {
596 if (const RecordType *FDTTy =
597 NewBaseType.getTypePtr()->getAs<RecordType>())
598 if (FDTTy->getDecl()->hasObjectMember())
599 Class->setHasObjectMember(true);
600 }
601
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000602 if (KnownBaseTypes[NewBaseType]) {
603 // C++ [class.mi]p3:
604 // A class shall not be specified as a direct base class of a
605 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000625
626 // Delete the remaining (good) base class specifiers, since their
627 // data has been copied into the CXXRecordDecl.
628 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000630
631 return Invalid;
632}
633
634/// ActOnBaseSpecifiers - Attach the given base specifiers to the
635/// class, after checking whether there are any duplicate base
636/// classes.
John McCalld226f652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000646
John McCall3cb0ebd2010-03-10 03:28:59 +0000647static CXXRecordDecl *GetClassForType(QualType T) {
648 if (const RecordType *RT = T->getAs<RecordType>())
649 return cast<CXXRecordDecl>(RT->getDecl());
650 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
651 return ICT->getDecl();
652 else
653 return 0;
654}
655
Douglas Gregora8f32e02009-10-06 17:59:45 +0000656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000664 return false;
665
John McCall3cb0ebd2010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000668 return false;
669
John McCall86ff3082010-02-04 22:26:26 +0000670 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
671 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000672}
673
674/// \brief Determine whether the type \p Derived is a C++ class that is
675/// derived from the type \p Base.
676bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
677 if (!getLangOptions().CPlusPlus)
678 return false;
679
John McCall3cb0ebd2010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000682 return false;
683
John McCall3cb0ebd2010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregora8f32e02009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000693 assert(BasePathArray.empty() && "Base path array must be empty!");
694 assert(Paths.isRecordingPaths() && "Must record paths!");
695
696 const CXXBasePath &Path = Paths.front();
697
698 // We first go backward and check if we have a virtual base.
699 // FIXME: It would be better if CXXBasePath had the base specifier for
700 // the nearest virtual base.
701 unsigned Start = 0;
702 for (unsigned I = Path.size(); I != 0; --I) {
703 if (Path[I - 1].Base->isVirtual()) {
704 Start = I - 1;
705 break;
706 }
707 }
708
709 // Now add all bases.
710 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000712}
713
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregora8f32e02009-10-06 17:59:45 +0000726/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
727/// conversion (where Derived and Base are class types) is
728/// well-formed, meaning that the conversion is unambiguous (and
729/// that all of the base classes are accessible). Returns true
730/// and emits a diagnostic if the code is ill-formed, returns false
731/// otherwise. Loc is the location where this routine should point to
732/// if there is an error, and Range is the source range to highlight
733/// if there is an error.
734bool
735Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000741 // First, determine whether the path from Derived to Base is
742 // ambiguous. This is slightly more expensive than checking whether
743 // the Derived to Base conversion exists, because here we need to
744 // explore multiple paths to determine if there is an ambiguity.
745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
746 /*DetectVirtual=*/false);
747 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(DerivationOkay &&
749 "Can only be used with a derived-to-base conversion");
750 (void)DerivationOkay;
751
752 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000753 if (InaccessibleBaseID) {
754 // Check that the base class can be accessed.
755 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
756 InaccessibleBaseID)) {
757 case AR_inaccessible:
758 return true;
759 case AR_accessible:
760 case AR_dependent:
761 case AR_delayed:
762 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000763 }
John McCall6b2accb2010-02-10 09:31:12 +0000764 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000770 }
771
772 // We know that the derived-to-base conversion is ambiguous, and
773 // we're going to produce a diagnostic. Perform the derived-to-base
774 // search just one more time to compute all of the possible paths so
775 // that we can print them out. This is more expensive than any of
776 // the previous derived-to-base checks we've done, but at this point
777 // performance isn't as much of an issue.
778 Paths.clear();
779 Paths.setRecordingPaths(true);
780 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(StillOkay && "Can only be used with a derived-to-base conversion");
782 (void)StillOkay;
783
784 // Build up a textual representation of the ambiguous paths, e.g.,
785 // D -> B -> A, that will be used to illustrate the ambiguous
786 // conversions in the diagnostic. We only print one of the paths
787 // to each base class subobject.
788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
789
790 Diag(Loc, AmbigiousBaseConvID)
791 << Derived << Base << PathDisplayStr << Range << Name;
792 return true;
793}
794
795bool
796Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806}
807
808
809/// @brief Builds a string representing ambiguous paths from a
810/// specific derived class to different subobjects of the same base
811/// class.
812///
813/// This function builds a string that can be used in error messages
814/// to show the different paths that one can take through the
815/// inheritance hierarchy to go from the derived class to different
816/// subobjects of a base class. The result looks something like this:
817/// @code
818/// struct D -> struct B -> struct A
819/// struct D -> struct C -> struct A
820/// @endcode
821std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
822 std::string PathDisplayStr;
823 std::set<unsigned> DisplayedPaths;
824 for (CXXBasePaths::paths_iterator Path = Paths.begin();
825 Path != Paths.end(); ++Path) {
826 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
827 // We haven't displayed a path to this particular base
828 // class subobject yet.
829 PathDisplayStr += "\n ";
830 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
831 for (CXXBasePath::const_iterator Element = Path->begin();
832 Element != Path->end(); ++Element)
833 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
834 }
835 }
836
837 return PathDisplayStr;
838}
839
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnara6206d532010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000853}
854
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000855/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
856/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
857/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000858/// any.
John McCalld226f652010-08-21 09:40:31 +0000859Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000862 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
863 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000865 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
866 DeclarationName Name = NameInfo.getName();
867 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000868
869 // For anonymous bitfields, the location should point to the type.
870 if (Loc.isInvalid())
871 Loc = D.getSourceRange().getBegin();
872
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873 Expr *BitWidth = static_cast<Expr*>(BW);
874 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000875
John McCall4bde1e12010-06-04 08:34:12 +0000876 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000877 assert(!DS.isFriendSpecified());
878
John McCall4bde1e12010-06-04 08:34:12 +0000879 bool isFunc = false;
880 if (D.isFunctionDeclarator())
881 isFunc = true;
882 else if (D.getNumTypeObjects() == 0 &&
883 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000884 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000885 isFunc = TDType->isFunctionType();
886 }
887
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888 // C++ 9.2p6: A member shall not be declared to have automatic storage
889 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000890 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
891 // data members and cannot be applied to names declared const or static,
892 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893 switch (DS.getStorageClassSpec()) {
894 case DeclSpec::SCS_unspecified:
895 case DeclSpec::SCS_typedef:
896 case DeclSpec::SCS_static:
897 // FALL THROUGH.
898 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000899 case DeclSpec::SCS_mutable:
900 if (isFunc) {
901 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000902 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000903 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000904 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Sebastian Redla11f42f2008-11-17 23:24:37 +0000906 // FIXME: It would be nicer if the keyword was ignored only for this
907 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000908 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000909 }
910 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000911 default:
912 if (DS.getStorageClassSpecLoc().isValid())
913 Diag(DS.getStorageClassSpecLoc(),
914 diag::err_storageclass_invalid_for_member);
915 else
916 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
917 D.getMutableDeclSpec().ClearStorageClassSpecs();
918 }
919
Sebastian Redl669d5d72008-11-14 23:42:31 +0000920 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
921 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000922 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000923
924 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000925 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000926 CXXScopeSpec &SS = D.getCXXScopeSpec();
927
928
929 if (SS.isSet() && !SS.isInvalid()) {
930 // The user provided a superfluous scope specifier inside a class
931 // definition:
932 //
933 // class X {
934 // int X::member;
935 // };
936 DeclContext *DC = 0;
937 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
938 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
939 << Name << FixItHint::CreateRemoval(SS.getRange());
940 else
941 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
942 << Name << SS.getRange();
943
944 SS.clear();
945 }
946
Douglas Gregor37b372b2009-08-20 22:52:58 +0000947 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +0000948 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000949 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
950 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000951 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000952 } else {
John McCalld226f652010-08-21 09:40:31 +0000953 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000954 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000955 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000956 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000957
958 // Non-instance-fields can't have a bitfield.
959 if (BitWidth) {
960 if (Member->isInvalidDecl()) {
961 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000962 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000963 // C++ 9.6p3: A bit-field shall not be a static member.
964 // "static member 'A' cannot be a bit-field"
965 Diag(Loc, diag::err_static_not_bitfield)
966 << Name << BitWidth->getSourceRange();
967 } else if (isa<TypedefDecl>(Member)) {
968 // "typedef member 'x' cannot be a bit-field"
969 Diag(Loc, diag::err_typedef_not_bitfield)
970 << Name << BitWidth->getSourceRange();
971 } else {
972 // A function typedef ("typedef int f(); f a;").
973 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
974 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000975 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000976 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner8b963ef2009-03-05 23:01:03 +0000979 BitWidth = 0;
980 Member->setInvalidDecl();
981 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000982
983 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Douglas Gregor37b372b2009-08-20 22:52:58 +0000985 // If we have declared a member function template, set the access of the
986 // templated declaration as well.
987 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
988 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000989 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000990
Douglas Gregor10bd3682008-11-17 22:58:34 +0000991 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992
Douglas Gregor021c3b32009-03-11 23:00:04 +0000993 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +0000994 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000995 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +0000996 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000997
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000998 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000999 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001000 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001001 }
John McCalld226f652010-08-21 09:40:31 +00001002 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003}
1004
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001005/// \brief Find the direct and/or virtual base specifiers that
1006/// correspond to the given base type, for use in base initialization
1007/// within a constructor.
1008static bool FindBaseInitializer(Sema &SemaRef,
1009 CXXRecordDecl *ClassDecl,
1010 QualType BaseType,
1011 const CXXBaseSpecifier *&DirectBaseSpec,
1012 const CXXBaseSpecifier *&VirtualBaseSpec) {
1013 // First, check for a direct base class.
1014 DirectBaseSpec = 0;
1015 for (CXXRecordDecl::base_class_const_iterator Base
1016 = ClassDecl->bases_begin();
1017 Base != ClassDecl->bases_end(); ++Base) {
1018 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1019 // We found a direct base of this type. That's what we're
1020 // initializing.
1021 DirectBaseSpec = &*Base;
1022 break;
1023 }
1024 }
1025
1026 // Check for a virtual base class.
1027 // FIXME: We might be able to short-circuit this if we know in advance that
1028 // there are no virtual bases.
1029 VirtualBaseSpec = 0;
1030 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1031 // We haven't found a base yet; search the class hierarchy for a
1032 // virtual base class.
1033 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1034 /*DetectVirtual=*/false);
1035 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1036 BaseType, Paths)) {
1037 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1038 Path != Paths.end(); ++Path) {
1039 if (Path->back().Base->isVirtual()) {
1040 VirtualBaseSpec = Path->back().Base;
1041 break;
1042 }
1043 }
1044 }
1045 }
1046
1047 return DirectBaseSpec || VirtualBaseSpec;
1048}
1049
Douglas Gregor7ad83902008-11-05 04:29:56 +00001050/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001051MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001052Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001053 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001054 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001055 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001056 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001057 SourceLocation IdLoc,
1058 SourceLocation LParenLoc,
1059 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001060 SourceLocation RParenLoc,
1061 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001062 if (!ConstructorD)
1063 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001065 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001066
1067 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001068 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001069 if (!Constructor) {
1070 // The user wrote a constructor initializer on a function that is
1071 // not a C++ constructor. Ignore the error for now, because we may
1072 // have more member initializers coming; we'll diagnose it just
1073 // once in ActOnMemInitializers.
1074 return true;
1075 }
1076
1077 CXXRecordDecl *ClassDecl = Constructor->getParent();
1078
1079 // C++ [class.base.init]p2:
1080 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001081 // constructor's class and, if not found in that scope, are looked
1082 // up in the scope containing the constructor's definition.
1083 // [Note: if the constructor's class contains a member with the
1084 // same name as a direct or virtual base class of the class, a
1085 // mem-initializer-id naming the member or base class and composed
1086 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001087 // mem-initializer-id for the hidden base class may be specified
1088 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001089 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001090 // Look for a member, first.
1091 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001092 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001093 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001094 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001095 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001096
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001097 if (Member) {
1098 if (EllipsisLoc.isValid())
1099 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1100 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1101
Francois Pichet00eb3f92010-12-04 09:14:42 +00001102 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001103 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001104 }
1105
Francois Pichet00eb3f92010-12-04 09:14:42 +00001106 // Handle anonymous union case.
1107 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001108 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1109 if (EllipsisLoc.isValid())
1110 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1111 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1112
Francois Pichet00eb3f92010-12-04 09:14:42 +00001113 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1114 NumArgs, IdLoc,
1115 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001116 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001117 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001118 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001119 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001120 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001121 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001122
1123 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001124 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001125 } else {
1126 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1127 LookupParsedName(R, S, &SS);
1128
1129 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1130 if (!TyD) {
1131 if (R.isAmbiguous()) return true;
1132
John McCallfd225442010-04-09 19:01:14 +00001133 // We don't want access-control diagnostics here.
1134 R.suppressDiagnostics();
1135
Douglas Gregor7a886e12010-01-19 06:46:48 +00001136 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1137 bool NotUnknownSpecialization = false;
1138 DeclContext *DC = computeDeclContext(SS, false);
1139 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1140 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1141
1142 if (!NotUnknownSpecialization) {
1143 // When the scope specifier can refer to a member of an unknown
1144 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001145 BaseType = CheckTypenameType(ETK_None,
1146 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001147 *MemberOrBase, SourceLocation(),
1148 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001149 if (BaseType.isNull())
1150 return true;
1151
Douglas Gregor7a886e12010-01-19 06:46:48 +00001152 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001153 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001154 }
1155 }
1156
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001157 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001158 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001159 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1160 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001161 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001162 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001163 // We have found a non-static data member with a similar
1164 // name to what was typed; complain and initialize that
1165 // member.
1166 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1167 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001168 << FixItHint::CreateReplacement(R.getNameLoc(),
1169 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001170 Diag(Member->getLocation(), diag::note_previous_decl)
1171 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001172
1173 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1174 LParenLoc, RParenLoc);
1175 }
1176 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1177 const CXXBaseSpecifier *DirectBaseSpec;
1178 const CXXBaseSpecifier *VirtualBaseSpec;
1179 if (FindBaseInitializer(*this, ClassDecl,
1180 Context.getTypeDeclType(Type),
1181 DirectBaseSpec, VirtualBaseSpec)) {
1182 // We have found a direct or virtual base class with a
1183 // similar name to what was typed; complain and initialize
1184 // that base class.
1185 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1186 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001187 << FixItHint::CreateReplacement(R.getNameLoc(),
1188 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001189
1190 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1191 : VirtualBaseSpec;
1192 Diag(BaseSpec->getSourceRange().getBegin(),
1193 diag::note_base_class_specified_here)
1194 << BaseSpec->getType()
1195 << BaseSpec->getSourceRange();
1196
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001197 TyD = Type;
1198 }
1199 }
1200 }
1201
Douglas Gregor7a886e12010-01-19 06:46:48 +00001202 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001203 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1204 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1205 return true;
1206 }
John McCall2b194412009-12-21 10:41:20 +00001207 }
1208
Douglas Gregor7a886e12010-01-19 06:46:48 +00001209 if (BaseType.isNull()) {
1210 BaseType = Context.getTypeDeclType(TyD);
1211 if (SS.isSet()) {
1212 NestedNameSpecifier *Qualifier =
1213 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001214
Douglas Gregor7a886e12010-01-19 06:46:48 +00001215 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001216 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001217 }
John McCall2b194412009-12-21 10:41:20 +00001218 }
1219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
John McCalla93c9342009-12-07 02:54:59 +00001221 if (!TInfo)
1222 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001223
John McCalla93c9342009-12-07 02:54:59 +00001224 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001225 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001226}
1227
John McCallb4190042009-11-04 23:02:40 +00001228/// Checks an initializer expression for use of uninitialized fields, such as
1229/// containing the field that is being initialized. Returns true if there is an
1230/// uninitialized field was used an updates the SourceLocation parameter; false
1231/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001232static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001233 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001234 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001235 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1236
Nick Lewycky43ad1822010-06-15 07:32:55 +00001237 if (isa<CallExpr>(S)) {
1238 // Do not descend into function calls or constructors, as the use
1239 // of an uninitialized field may be valid. One would have to inspect
1240 // the contents of the function/ctor to determine if it is safe or not.
1241 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1242 // may be safe, depending on what the function/ctor does.
1243 return false;
1244 }
1245 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1246 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001247
1248 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1249 // The member expression points to a static data member.
1250 assert(VD->isStaticDataMember() &&
1251 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001252 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001253 return false;
1254 }
1255
1256 if (isa<EnumConstantDecl>(RhsField)) {
1257 // The member expression points to an enum.
1258 return false;
1259 }
1260
John McCallb4190042009-11-04 23:02:40 +00001261 if (RhsField == LhsField) {
1262 // Initializing a field with itself. Throw a warning.
1263 // But wait; there are exceptions!
1264 // Exception #1: The field may not belong to this record.
1265 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001266 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001267 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1268 // Even though the field matches, it does not belong to this record.
1269 return false;
1270 }
1271 // None of the exceptions triggered; return true to indicate an
1272 // uninitialized field was used.
1273 *L = ME->getMemberLoc();
1274 return true;
1275 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001276 } else if (isa<SizeOfAlignOfExpr>(S)) {
1277 // sizeof/alignof doesn't reference contents, do not warn.
1278 return false;
1279 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1280 // address-of doesn't reference contents (the pointer may be dereferenced
1281 // in the same expression but it would be rare; and weird).
1282 if (UOE->getOpcode() == UO_AddrOf)
1283 return false;
John McCallb4190042009-11-04 23:02:40 +00001284 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001285 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1286 it != e; ++it) {
1287 if (!*it) {
1288 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001289 continue;
1290 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001291 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1292 return true;
John McCallb4190042009-11-04 23:02:40 +00001293 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001294 return false;
John McCallb4190042009-11-04 23:02:40 +00001295}
1296
John McCallf312b1e2010-08-26 23:41:50 +00001297MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001298Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001299 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001300 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001301 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001302 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1303 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1304 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001305 "Member must be a FieldDecl or IndirectFieldDecl");
1306
Douglas Gregor464b2f02010-11-05 22:21:31 +00001307 if (Member->isInvalidDecl())
1308 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001309
John McCallb4190042009-11-04 23:02:40 +00001310 // Diagnose value-uses of fields to initialize themselves, e.g.
1311 // foo(foo)
1312 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001313 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001314 for (unsigned i = 0; i < NumArgs; ++i) {
1315 SourceLocation L;
1316 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1317 // FIXME: Return true in the case when other fields are used before being
1318 // uninitialized. For example, let this field be the i'th field. When
1319 // initializing the i'th field, throw a warning if any of the >= i'th
1320 // fields are used, as they are not yet initialized.
1321 // Right now we are only handling the case where the i'th field uses
1322 // itself in its initializer.
1323 Diag(L, diag::warn_field_is_uninit);
1324 }
1325 }
1326
Eli Friedman59c04372009-07-29 19:44:27 +00001327 bool HasDependentArg = false;
1328 for (unsigned i = 0; i < NumArgs; i++)
1329 HasDependentArg |= Args[i]->isTypeDependent();
1330
Chandler Carruth894aed92010-12-06 09:23:57 +00001331 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001332 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001333 // Can't check initialization for a member of dependent type or when
1334 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001335 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1336 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001337
1338 // Erase any temporaries within this evaluation context; we're not
1339 // going to track them in the AST, since we'll be rebuilding the
1340 // ASTs during template instantiation.
1341 ExprTemporaries.erase(
1342 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1343 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001344 } else {
1345 // Initialize the member.
1346 InitializedEntity MemberEntity =
1347 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1348 : InitializedEntity::InitializeMember(IndirectMember, 0);
1349 InitializationKind Kind =
1350 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001351
Chandler Carruth894aed92010-12-06 09:23:57 +00001352 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1353
1354 ExprResult MemberInit =
1355 InitSeq.Perform(*this, MemberEntity, Kind,
1356 MultiExprArg(*this, Args, NumArgs), 0);
1357 if (MemberInit.isInvalid())
1358 return true;
1359
1360 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1361
1362 // C++0x [class.base.init]p7:
1363 // The initialization of each base and member constitutes a
1364 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001365 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001366 if (MemberInit.isInvalid())
1367 return true;
1368
1369 // If we are in a dependent context, template instantiation will
1370 // perform this type-checking again. Just save the arguments that we
1371 // received in a ParenListExpr.
1372 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1373 // of the information that we have about the member
1374 // initializer. However, deconstructing the ASTs is a dicey process,
1375 // and this approach is far more likely to get the corner cases right.
1376 if (CurContext->isDependentContext())
1377 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1378 RParenLoc);
1379 else
1380 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001381 }
1382
Chandler Carruth894aed92010-12-06 09:23:57 +00001383 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001384 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001385 IdLoc, LParenLoc, Init,
1386 RParenLoc);
1387 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001388 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001389 IdLoc, LParenLoc, Init,
1390 RParenLoc);
1391 }
Eli Friedman59c04372009-07-29 19:44:27 +00001392}
1393
John McCallf312b1e2010-08-26 23:41:50 +00001394MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001395Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1396 Expr **Args, unsigned NumArgs,
1397 SourceLocation LParenLoc,
1398 SourceLocation RParenLoc,
1399 CXXRecordDecl *ClassDecl,
1400 SourceLocation EllipsisLoc) {
1401 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1402 if (!LangOpts.CPlusPlus0x)
1403 return Diag(Loc, diag::err_delegation_0x_only)
1404 << TInfo->getTypeLoc().getLocalSourceRange();
1405
1406 return Diag(Loc, diag::err_delegation_unimplemented)
1407 << TInfo->getTypeLoc().getLocalSourceRange();
1408}
1409
1410MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001411Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001412 Expr **Args, unsigned NumArgs,
1413 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001414 CXXRecordDecl *ClassDecl,
1415 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001416 bool HasDependentArg = false;
1417 for (unsigned i = 0; i < NumArgs; i++)
1418 HasDependentArg |= Args[i]->isTypeDependent();
1419
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001420 SourceLocation BaseLoc
1421 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1422
1423 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1424 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1425 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1426
1427 // C++ [class.base.init]p2:
1428 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001429 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001430 // of that class, the mem-initializer is ill-formed. A
1431 // mem-initializer-list can initialize a base class using any
1432 // name that denotes that base class type.
1433 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1434
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001435 if (EllipsisLoc.isValid()) {
1436 // This is a pack expansion.
1437 if (!BaseType->containsUnexpandedParameterPack()) {
1438 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1439 << SourceRange(BaseLoc, RParenLoc);
1440
1441 EllipsisLoc = SourceLocation();
1442 }
1443 } else {
1444 // Check for any unexpanded parameter packs.
1445 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1446 return true;
1447
1448 for (unsigned I = 0; I != NumArgs; ++I)
1449 if (DiagnoseUnexpandedParameterPack(Args[I]))
1450 return true;
1451 }
1452
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001453 // Check for direct and virtual base classes.
1454 const CXXBaseSpecifier *DirectBaseSpec = 0;
1455 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1456 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001457 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1458 BaseType))
1459 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1460 LParenLoc, RParenLoc, ClassDecl,
1461 EllipsisLoc);
1462
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001463 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1464 VirtualBaseSpec);
1465
1466 // C++ [base.class.init]p2:
1467 // Unless the mem-initializer-id names a nonstatic data member of the
1468 // constructor's class or a direct or virtual base of that class, the
1469 // mem-initializer is ill-formed.
1470 if (!DirectBaseSpec && !VirtualBaseSpec) {
1471 // If the class has any dependent bases, then it's possible that
1472 // one of those types will resolve to the same type as
1473 // BaseType. Therefore, just treat this as a dependent base
1474 // class initialization. FIXME: Should we try to check the
1475 // initialization anyway? It seems odd.
1476 if (ClassDecl->hasAnyDependentBases())
1477 Dependent = true;
1478 else
1479 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1480 << BaseType << Context.getTypeDeclType(ClassDecl)
1481 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1482 }
1483 }
1484
1485 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001486 // Can't check initialization for a base of dependent type or when
1487 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001488 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001489 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1490 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001491
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001492 // Erase any temporaries within this evaluation context; we're not
1493 // going to track them in the AST, since we'll be rebuilding the
1494 // ASTs during template instantiation.
1495 ExprTemporaries.erase(
1496 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1497 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Sean Huntcbb67482011-01-08 20:30:50 +00001499 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001500 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001501 LParenLoc,
1502 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001503 RParenLoc,
1504 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001505 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001506
1507 // C++ [base.class.init]p2:
1508 // If a mem-initializer-id is ambiguous because it designates both
1509 // a direct non-virtual base class and an inherited virtual base
1510 // class, the mem-initializer is ill-formed.
1511 if (DirectBaseSpec && VirtualBaseSpec)
1512 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001513 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001514
1515 CXXBaseSpecifier *BaseSpec
1516 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1517 if (!BaseSpec)
1518 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1519
1520 // Initialize the base.
1521 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001522 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001523 InitializationKind Kind =
1524 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1525
1526 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1527
John McCall60d7b3a2010-08-24 06:29:42 +00001528 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001529 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001530 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001531 if (BaseInit.isInvalid())
1532 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001533
1534 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001535
1536 // C++0x [class.base.init]p7:
1537 // The initialization of each base and member constitutes a
1538 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001539 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001540 if (BaseInit.isInvalid())
1541 return true;
1542
1543 // If we are in a dependent context, template instantiation will
1544 // perform this type-checking again. Just save the arguments that we
1545 // received in a ParenListExpr.
1546 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1547 // of the information that we have about the base
1548 // initializer. However, deconstructing the ASTs is a dicey process,
1549 // and this approach is far more likely to get the corner cases right.
1550 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001551 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001552 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1553 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001554 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001555 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001556 LParenLoc,
1557 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001558 RParenLoc,
1559 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001560 }
1561
Sean Huntcbb67482011-01-08 20:30:50 +00001562 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001563 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001564 LParenLoc,
1565 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001566 RParenLoc,
1567 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001568}
1569
Anders Carlssone5ef7402010-04-23 03:10:23 +00001570/// ImplicitInitializerKind - How an implicit base or member initializer should
1571/// initialize its base or member.
1572enum ImplicitInitializerKind {
1573 IIK_Default,
1574 IIK_Copy,
1575 IIK_Move
1576};
1577
Anders Carlssondefefd22010-04-23 02:00:02 +00001578static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001579BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001580 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001581 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001582 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001583 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001584 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001585 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1586 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001587
John McCall60d7b3a2010-08-24 06:29:42 +00001588 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001589
1590 switch (ImplicitInitKind) {
1591 case IIK_Default: {
1592 InitializationKind InitKind
1593 = InitializationKind::CreateDefault(Constructor->getLocation());
1594 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1595 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001596 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001597 break;
1598 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001599
Anders Carlssone5ef7402010-04-23 03:10:23 +00001600 case IIK_Copy: {
1601 ParmVarDecl *Param = Constructor->getParamDecl(0);
1602 QualType ParamType = Param->getType().getNonReferenceType();
1603
1604 Expr *CopyCtorArg =
1605 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001606 Constructor->getLocation(), ParamType,
1607 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001608
Anders Carlssonc7957502010-04-24 22:02:54 +00001609 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001610 QualType ArgTy =
1611 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1612 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001613
1614 CXXCastPath BasePath;
1615 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001616 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001617 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001618 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001619
Anders Carlssone5ef7402010-04-23 03:10:23 +00001620 InitializationKind InitKind
1621 = InitializationKind::CreateDirect(Constructor->getLocation(),
1622 SourceLocation(), SourceLocation());
1623 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1624 &CopyCtorArg, 1);
1625 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001626 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001627 break;
1628 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001629
Anders Carlssone5ef7402010-04-23 03:10:23 +00001630 case IIK_Move:
1631 assert(false && "Unhandled initializer kind!");
1632 }
John McCall9ae2f072010-08-23 23:25:46 +00001633
Douglas Gregor53c374f2010-12-07 00:41:46 +00001634 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001635 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001636 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001637
Anders Carlssondefefd22010-04-23 02:00:02 +00001638 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001639 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001640 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1641 SourceLocation()),
1642 BaseSpec->isVirtual(),
1643 SourceLocation(),
1644 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001645 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001646 SourceLocation());
1647
Anders Carlssondefefd22010-04-23 02:00:02 +00001648 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001649}
1650
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001651static bool
1652BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001653 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001654 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001655 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001656 if (Field->isInvalidDecl())
1657 return true;
1658
Chandler Carruthf186b542010-06-29 23:50:44 +00001659 SourceLocation Loc = Constructor->getLocation();
1660
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001661 if (ImplicitInitKind == IIK_Copy) {
1662 ParmVarDecl *Param = Constructor->getParamDecl(0);
1663 QualType ParamType = Param->getType().getNonReferenceType();
1664
1665 Expr *MemberExprBase =
1666 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001667 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001668
1669 // Build a reference to this field within the parameter.
1670 CXXScopeSpec SS;
1671 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1672 Sema::LookupMemberName);
1673 MemberLookup.addDecl(Field, AS_public);
1674 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001675 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001676 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001677 ParamType, Loc,
1678 /*IsArrow=*/false,
1679 SS,
1680 /*FirstQualifierInScope=*/0,
1681 MemberLookup,
1682 /*TemplateArgs=*/0);
1683 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001684 return true;
1685
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001686 // When the field we are copying is an array, create index variables for
1687 // each dimension of the array. We use these index variables to subscript
1688 // the source array, and other clients (e.g., CodeGen) will perform the
1689 // necessary iteration with these index variables.
1690 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1691 QualType BaseType = Field->getType();
1692 QualType SizeType = SemaRef.Context.getSizeType();
1693 while (const ConstantArrayType *Array
1694 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1695 // Create the iteration variable for this array index.
1696 IdentifierInfo *IterationVarName = 0;
1697 {
1698 llvm::SmallString<8> Str;
1699 llvm::raw_svector_ostream OS(Str);
1700 OS << "__i" << IndexVariables.size();
1701 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1702 }
1703 VarDecl *IterationVar
1704 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1705 IterationVarName, SizeType,
1706 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001707 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001708 IndexVariables.push_back(IterationVar);
1709
1710 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001711 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001712 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001713 assert(!IterationVarRef.isInvalid() &&
1714 "Reference to invented variable cannot fail!");
1715
1716 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001717 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001718 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001719 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001720 Loc);
1721 if (CopyCtorArg.isInvalid())
1722 return true;
1723
1724 BaseType = Array->getElementType();
1725 }
1726
1727 // Construct the entity that we will be initializing. For an array, this
1728 // will be first element in the array, which may require several levels
1729 // of array-subscript entities.
1730 llvm::SmallVector<InitializedEntity, 4> Entities;
1731 Entities.reserve(1 + IndexVariables.size());
1732 Entities.push_back(InitializedEntity::InitializeMember(Field));
1733 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1734 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1735 0,
1736 Entities.back()));
1737
1738 // Direct-initialize to use the copy constructor.
1739 InitializationKind InitKind =
1740 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1741
1742 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1743 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1744 &CopyCtorArgE, 1);
1745
John McCall60d7b3a2010-08-24 06:29:42 +00001746 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001747 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001748 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001749 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001750 if (MemberInit.isInvalid())
1751 return true;
1752
1753 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001754 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001755 MemberInit.takeAs<Expr>(), Loc,
1756 IndexVariables.data(),
1757 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001758 return false;
1759 }
1760
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001761 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1762
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001763 QualType FieldBaseElementType =
1764 SemaRef.Context.getBaseElementType(Field->getType());
1765
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001766 if (FieldBaseElementType->isRecordType()) {
1767 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001768 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001769 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001770
1771 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001772 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001773 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001774
Douglas Gregor53c374f2010-12-07 00:41:46 +00001775 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001776 if (MemberInit.isInvalid())
1777 return true;
1778
1779 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001780 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001781 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001782 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001783 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001784 return false;
1785 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001786
1787 if (FieldBaseElementType->isReferenceType()) {
1788 SemaRef.Diag(Constructor->getLocation(),
1789 diag::err_uninitialized_member_in_ctor)
1790 << (int)Constructor->isImplicit()
1791 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1792 << 0 << Field->getDeclName();
1793 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1794 return true;
1795 }
1796
1797 if (FieldBaseElementType.isConstQualified()) {
1798 SemaRef.Diag(Constructor->getLocation(),
1799 diag::err_uninitialized_member_in_ctor)
1800 << (int)Constructor->isImplicit()
1801 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1802 << 1 << Field->getDeclName();
1803 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1804 return true;
1805 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001806
1807 // Nothing to initialize.
1808 CXXMemberInit = 0;
1809 return false;
1810}
John McCallf1860e52010-05-20 23:23:51 +00001811
1812namespace {
1813struct BaseAndFieldInfo {
1814 Sema &S;
1815 CXXConstructorDecl *Ctor;
1816 bool AnyErrorsInInits;
1817 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001818 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1819 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001820
1821 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1822 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1823 // FIXME: Handle implicit move constructors.
1824 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1825 IIK = IIK_Copy;
1826 else
1827 IIK = IIK_Default;
1828 }
1829};
1830}
1831
1832static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1833 FieldDecl *Top, FieldDecl *Field) {
1834
Chandler Carruthe861c602010-06-30 02:59:29 +00001835 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00001836 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001837 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001838 return false;
1839 }
1840
1841 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1842 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1843 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001844 CXXRecordDecl *FieldClassDecl
1845 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001846
1847 // Even though union members never have non-trivial default
1848 // constructions in C++03, we still build member initializers for aggregate
1849 // record types which can be union members, and C++0x allows non-trivial
1850 // default constructors for union members, so we ensure that only one
1851 // member is initialized for these.
1852 if (FieldClassDecl->isUnion()) {
1853 // First check for an explicit initializer for one field.
1854 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1855 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00001856 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001857 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001858
1859 // Once we've initialized a field of an anonymous union, the union
1860 // field in the class is also initialized, so exit immediately.
1861 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001862 } else if ((*FA)->isAnonymousStructOrUnion()) {
1863 if (CollectFieldInitializer(Info, Top, *FA))
1864 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001865 }
1866 }
1867
1868 // Fallthrough and construct a default initializer for the union as
1869 // a whole, which can call its default constructor if such a thing exists
1870 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1871 // behavior going forward with C++0x, when anonymous unions there are
1872 // finalized, we should revisit this.
1873 } else {
1874 // For structs, we simply descend through to initialize all members where
1875 // necessary.
1876 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1877 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1878 if (CollectFieldInitializer(Info, Top, *FA))
1879 return true;
1880 }
1881 }
John McCallf1860e52010-05-20 23:23:51 +00001882 }
1883
1884 // Don't try to build an implicit initializer if there were semantic
1885 // errors in any of the initializers (and therefore we might be
1886 // missing some that the user actually wrote).
1887 if (Info.AnyErrorsInInits)
1888 return false;
1889
Sean Huntcbb67482011-01-08 20:30:50 +00001890 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00001891 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1892 return true;
John McCallf1860e52010-05-20 23:23:51 +00001893
Francois Pichet00eb3f92010-12-04 09:14:42 +00001894 if (Init)
1895 Info.AllToInit.push_back(Init);
1896
John McCallf1860e52010-05-20 23:23:51 +00001897 return false;
1898}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001899
Eli Friedman80c30da2009-11-09 19:20:36 +00001900bool
Sean Huntcbb67482011-01-08 20:30:50 +00001901Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1902 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001903 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001904 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001905 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001906 // Just store the initializers as written, they will be checked during
1907 // instantiation.
1908 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00001909 Constructor->setNumCtorInitializers(NumInitializers);
1910 CXXCtorInitializer **baseOrMemberInitializers =
1911 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001912 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00001913 NumInitializers * sizeof(CXXCtorInitializer*));
1914 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001915 }
1916
1917 return false;
1918 }
1919
John McCallf1860e52010-05-20 23:23:51 +00001920 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001921
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001922 // We need to build the initializer AST according to order of construction
1923 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001924 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001925 if (!ClassDecl)
1926 return true;
1927
Eli Friedman80c30da2009-11-09 19:20:36 +00001928 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001930 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00001931 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001932
1933 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001934 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001935 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00001936 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001937 }
1938
Anders Carlsson711f34a2010-04-21 19:52:01 +00001939 // Keep track of the direct virtual bases.
1940 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1941 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1942 E = ClassDecl->bases_end(); I != E; ++I) {
1943 if (I->isVirtual())
1944 DirectVBases.insert(I);
1945 }
1946
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001947 // Push virtual bases before others.
1948 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1949 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1950
Sean Huntcbb67482011-01-08 20:30:50 +00001951 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001952 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1953 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001954 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001955 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00001956 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001957 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001958 VBase, IsInheritedVirtualBase,
1959 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001960 HadError = true;
1961 continue;
1962 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001963
John McCallf1860e52010-05-20 23:23:51 +00001964 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001965 }
1966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967
John McCallf1860e52010-05-20 23:23:51 +00001968 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001969 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1970 E = ClassDecl->bases_end(); Base != E; ++Base) {
1971 // Virtuals are in the virtual base list and already constructed.
1972 if (Base->isVirtual())
1973 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Sean Huntcbb67482011-01-08 20:30:50 +00001975 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001976 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1977 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001978 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00001979 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001981 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001982 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001983 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001984 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001985 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001986
John McCallf1860e52010-05-20 23:23:51 +00001987 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001988 }
1989 }
Mike Stump1eb44332009-09-09 15:08:12 +00001990
John McCallf1860e52010-05-20 23:23:51 +00001991 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001993 E = ClassDecl->field_end(); Field != E; ++Field) {
1994 if ((*Field)->getType()->isIncompleteArrayType()) {
1995 assert(ClassDecl->hasFlexibleArrayMember() &&
1996 "Incomplete array type is not valid");
1997 continue;
1998 }
John McCallf1860e52010-05-20 23:23:51 +00001999 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002000 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
John McCallf1860e52010-05-20 23:23:51 +00002003 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002004 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002005 Constructor->setNumCtorInitializers(NumInitializers);
2006 CXXCtorInitializer **baseOrMemberInitializers =
2007 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002008 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002009 NumInitializers * sizeof(CXXCtorInitializer*));
2010 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002011
John McCallef027fe2010-03-16 21:39:52 +00002012 // Constructors implicitly reference the base and member
2013 // destructors.
2014 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2015 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002016 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002017
2018 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002019}
2020
Eli Friedman6347f422009-07-21 19:28:10 +00002021static void *GetKeyForTopLevelField(FieldDecl *Field) {
2022 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002023 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002024 if (RT->getDecl()->isAnonymousStructOrUnion())
2025 return static_cast<void *>(RT->getDecl());
2026 }
2027 return static_cast<void *>(Field);
2028}
2029
Anders Carlssonea356fb2010-04-02 05:42:15 +00002030static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2031 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002032}
2033
Anders Carlssonea356fb2010-04-02 05:42:15 +00002034static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002035 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002036 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002037 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002038
Eli Friedman6347f422009-07-21 19:28:10 +00002039 // For fields injected into the class via declaration of an anonymous union,
2040 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002041 FieldDecl *Field = Member->getAnyMember();
2042
John McCall3c3ccdb2010-04-10 09:28:51 +00002043 // If the field is a member of an anonymous struct or union, our key
2044 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002045 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002046 if (RD->isAnonymousStructOrUnion()) {
2047 while (true) {
2048 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2049 if (Parent->isAnonymousStructOrUnion())
2050 RD = Parent;
2051 else
2052 break;
2053 }
2054
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002055 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002058 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002059}
2060
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002061static void
2062DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002063 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002064 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002065 unsigned NumInits) {
2066 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002067 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002069 // Don't check initializers order unless the warning is enabled at the
2070 // location of at least one initializer.
2071 bool ShouldCheckOrder = false;
2072 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002073 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002074 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2075 Init->getSourceLocation())
2076 != Diagnostic::Ignored) {
2077 ShouldCheckOrder = true;
2078 break;
2079 }
2080 }
2081 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002082 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002083
John McCalld6ca8da2010-04-10 07:37:23 +00002084 // Build the list of bases and members in the order that they'll
2085 // actually be initialized. The explicit initializers should be in
2086 // this same order but may be missing things.
2087 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Anders Carlsson071d6102010-04-02 03:38:04 +00002089 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2090
John McCalld6ca8da2010-04-10 07:37:23 +00002091 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002092 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002093 ClassDecl->vbases_begin(),
2094 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002095 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002096
John McCalld6ca8da2010-04-10 07:37:23 +00002097 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002098 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002099 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002100 if (Base->isVirtual())
2101 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002103 }
Mike Stump1eb44332009-09-09 15:08:12 +00002104
John McCalld6ca8da2010-04-10 07:37:23 +00002105 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2107 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002108 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002109
John McCalld6ca8da2010-04-10 07:37:23 +00002110 unsigned NumIdealInits = IdealInitKeys.size();
2111 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002112
Sean Huntcbb67482011-01-08 20:30:50 +00002113 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002114 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002115 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002116 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002117
2118 // Scan forward to try to find this initializer in the idealized
2119 // initializers list.
2120 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2121 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002122 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002123
2124 // If we didn't find this initializer, it must be because we
2125 // scanned past it on a previous iteration. That can only
2126 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002127 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002128 Sema::SemaDiagnosticBuilder D =
2129 SemaRef.Diag(PrevInit->getSourceLocation(),
2130 diag::warn_initializer_out_of_order);
2131
Francois Pichet00eb3f92010-12-04 09:14:42 +00002132 if (PrevInit->isAnyMemberInitializer())
2133 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002134 else
2135 D << 1 << PrevInit->getBaseClassInfo()->getType();
2136
Francois Pichet00eb3f92010-12-04 09:14:42 +00002137 if (Init->isAnyMemberInitializer())
2138 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002139 else
2140 D << 1 << Init->getBaseClassInfo()->getType();
2141
2142 // Move back to the initializer's location in the ideal list.
2143 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2144 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002145 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002146
2147 assert(IdealIndex != NumIdealInits &&
2148 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002149 }
John McCalld6ca8da2010-04-10 07:37:23 +00002150
2151 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002152 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002153}
2154
John McCall3c3ccdb2010-04-10 09:28:51 +00002155namespace {
2156bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002157 CXXCtorInitializer *Init,
2158 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002159 if (!PrevInit) {
2160 PrevInit = Init;
2161 return false;
2162 }
2163
2164 if (FieldDecl *Field = Init->getMember())
2165 S.Diag(Init->getSourceLocation(),
2166 diag::err_multiple_mem_initialization)
2167 << Field->getDeclName()
2168 << Init->getSourceRange();
2169 else {
2170 Type *BaseClass = Init->getBaseClass();
2171 assert(BaseClass && "neither field nor base");
2172 S.Diag(Init->getSourceLocation(),
2173 diag::err_multiple_base_initialization)
2174 << QualType(BaseClass, 0)
2175 << Init->getSourceRange();
2176 }
2177 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2178 << 0 << PrevInit->getSourceRange();
2179
2180 return true;
2181}
2182
Sean Huntcbb67482011-01-08 20:30:50 +00002183typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002184typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2185
2186bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002187 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002188 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002189 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002190 RecordDecl *Parent = Field->getParent();
2191 if (!Parent->isAnonymousStructOrUnion())
2192 return false;
2193
2194 NamedDecl *Child = Field;
2195 do {
2196 if (Parent->isUnion()) {
2197 UnionEntry &En = Unions[Parent];
2198 if (En.first && En.first != Child) {
2199 S.Diag(Init->getSourceLocation(),
2200 diag::err_multiple_mem_union_initialization)
2201 << Field->getDeclName()
2202 << Init->getSourceRange();
2203 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2204 << 0 << En.second->getSourceRange();
2205 return true;
2206 } else if (!En.first) {
2207 En.first = Child;
2208 En.second = Init;
2209 }
2210 }
2211
2212 Child = Parent;
2213 Parent = cast<RecordDecl>(Parent->getDeclContext());
2214 } while (Parent->isAnonymousStructOrUnion());
2215
2216 return false;
2217}
2218}
2219
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002220/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002221void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002222 SourceLocation ColonLoc,
2223 MemInitTy **meminits, unsigned NumMemInits,
2224 bool AnyErrors) {
2225 if (!ConstructorDecl)
2226 return;
2227
2228 AdjustDeclIfTemplate(ConstructorDecl);
2229
2230 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002231 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002232
2233 if (!Constructor) {
2234 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2235 return;
2236 }
2237
Sean Huntcbb67482011-01-08 20:30:50 +00002238 CXXCtorInitializer **MemInits =
2239 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002240
2241 // Mapping for the duplicate initializers check.
2242 // For member initializers, this is keyed with a FieldDecl*.
2243 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002244 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002245
2246 // Mapping for the inconsistent anonymous-union initializers check.
2247 RedundantUnionMap MemberUnions;
2248
Anders Carlssonea356fb2010-04-02 05:42:15 +00002249 bool HadError = false;
2250 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002251 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002252
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002253 // Set the source order index.
2254 Init->setSourceOrder(i);
2255
Francois Pichet00eb3f92010-12-04 09:14:42 +00002256 if (Init->isAnyMemberInitializer()) {
2257 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002258 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2259 CheckRedundantUnionInit(*this, Init, MemberUnions))
2260 HadError = true;
2261 } else {
2262 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2263 if (CheckRedundantInit(*this, Init, Members[Key]))
2264 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002265 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002266 }
2267
Anders Carlssonea356fb2010-04-02 05:42:15 +00002268 if (HadError)
2269 return;
2270
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002271 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002272
Sean Huntcbb67482011-01-08 20:30:50 +00002273 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002274}
2275
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002276void
John McCallef027fe2010-03-16 21:39:52 +00002277Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2278 CXXRecordDecl *ClassDecl) {
2279 // Ignore dependent contexts.
2280 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002281 return;
John McCall58e6f342010-03-16 05:22:47 +00002282
2283 // FIXME: all the access-control diagnostics are positioned on the
2284 // field/base declaration. That's probably good; that said, the
2285 // user might reasonably want to know why the destructor is being
2286 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002287
Anders Carlsson9f853df2009-11-17 04:44:12 +00002288 // Non-static data members.
2289 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2290 E = ClassDecl->field_end(); I != E; ++I) {
2291 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002292 if (Field->isInvalidDecl())
2293 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002294 QualType FieldType = Context.getBaseElementType(Field->getType());
2295
2296 const RecordType* RT = FieldType->getAs<RecordType>();
2297 if (!RT)
2298 continue;
2299
2300 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2301 if (FieldClassDecl->hasTrivialDestructor())
2302 continue;
2303
Douglas Gregordb89f282010-07-01 22:47:18 +00002304 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002305 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002306 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002307 << Field->getDeclName()
2308 << FieldType);
2309
John McCallef027fe2010-03-16 21:39:52 +00002310 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002311 }
2312
John McCall58e6f342010-03-16 05:22:47 +00002313 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2314
Anders Carlsson9f853df2009-11-17 04:44:12 +00002315 // Bases.
2316 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2317 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002318 // Bases are always records in a well-formed non-dependent class.
2319 const RecordType *RT = Base->getType()->getAs<RecordType>();
2320
2321 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002322 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002323 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002324
2325 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002326 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002327 if (BaseClassDecl->hasTrivialDestructor())
2328 continue;
John McCall58e6f342010-03-16 05:22:47 +00002329
Douglas Gregordb89f282010-07-01 22:47:18 +00002330 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002331
2332 // FIXME: caret should be on the start of the class name
2333 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002334 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002335 << Base->getType()
2336 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002337
John McCallef027fe2010-03-16 21:39:52 +00002338 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002339 }
2340
2341 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002342 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2343 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002344
2345 // Bases are always records in a well-formed non-dependent class.
2346 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2347
2348 // Ignore direct virtual bases.
2349 if (DirectVirtualBases.count(RT))
2350 continue;
2351
Anders Carlsson9f853df2009-11-17 04:44:12 +00002352 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002354 if (BaseClassDecl->hasTrivialDestructor())
2355 continue;
John McCall58e6f342010-03-16 05:22:47 +00002356
Douglas Gregordb89f282010-07-01 22:47:18 +00002357 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002358 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002359 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002360 << VBase->getType());
2361
John McCallef027fe2010-03-16 21:39:52 +00002362 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002363 }
2364}
2365
John McCalld226f652010-08-21 09:40:31 +00002366void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002367 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002368 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Mike Stump1eb44332009-09-09 15:08:12 +00002370 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002371 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002372 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002373}
2374
Mike Stump1eb44332009-09-09 15:08:12 +00002375bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002376 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002377 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002378 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002379 else
John McCall94c3b562010-08-18 09:41:07 +00002380 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002381}
2382
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002383bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002384 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002385 if (!getLangOptions().CPlusPlus)
2386 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002387
Anders Carlsson11f21a02009-03-23 19:10:31 +00002388 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002389 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Ted Kremenek6217b802009-07-29 21:53:49 +00002391 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002392 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002393 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002394 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002396 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002397 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002398 }
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Ted Kremenek6217b802009-07-29 21:53:49 +00002400 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002401 if (!RT)
2402 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002403
John McCall86ff3082010-02-04 22:26:26 +00002404 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002405
John McCall94c3b562010-08-18 09:41:07 +00002406 // We can't answer whether something is abstract until it has a
2407 // definition. If it's currently being defined, we'll walk back
2408 // over all the declarations when we have a full definition.
2409 const CXXRecordDecl *Def = RD->getDefinition();
2410 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002411 return false;
2412
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002413 if (!RD->isAbstract())
2414 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002415
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002416 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002417 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002418
John McCall94c3b562010-08-18 09:41:07 +00002419 return true;
2420}
2421
2422void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2423 // Check if we've already emitted the list of pure virtual functions
2424 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002425 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002426 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002428 CXXFinalOverriderMap FinalOverriders;
2429 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002431 // Keep a set of seen pure methods so we won't diagnose the same method
2432 // more than once.
2433 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2434
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002435 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2436 MEnd = FinalOverriders.end();
2437 M != MEnd;
2438 ++M) {
2439 for (OverridingMethods::iterator SO = M->second.begin(),
2440 SOEnd = M->second.end();
2441 SO != SOEnd; ++SO) {
2442 // C++ [class.abstract]p4:
2443 // A class is abstract if it contains or inherits at least one
2444 // pure virtual function for which the final overrider is pure
2445 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002447 //
2448 if (SO->second.size() != 1)
2449 continue;
2450
2451 if (!SO->second.front().Method->isPure())
2452 continue;
2453
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002454 if (!SeenPureMethods.insert(SO->second.front().Method))
2455 continue;
2456
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002457 Diag(SO->second.front().Method->getLocation(),
2458 diag::note_pure_virtual_function)
2459 << SO->second.front().Method->getDeclName();
2460 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002461 }
2462
2463 if (!PureVirtualClassDiagSet)
2464 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2465 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002466}
2467
Anders Carlsson8211eff2009-03-24 01:19:16 +00002468namespace {
John McCall94c3b562010-08-18 09:41:07 +00002469struct AbstractUsageInfo {
2470 Sema &S;
2471 CXXRecordDecl *Record;
2472 CanQualType AbstractType;
2473 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002474
John McCall94c3b562010-08-18 09:41:07 +00002475 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2476 : S(S), Record(Record),
2477 AbstractType(S.Context.getCanonicalType(
2478 S.Context.getTypeDeclType(Record))),
2479 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002480
John McCall94c3b562010-08-18 09:41:07 +00002481 void DiagnoseAbstractType() {
2482 if (Invalid) return;
2483 S.DiagnoseAbstractType(Record);
2484 Invalid = true;
2485 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002486
John McCall94c3b562010-08-18 09:41:07 +00002487 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2488};
2489
2490struct CheckAbstractUsage {
2491 AbstractUsageInfo &Info;
2492 const NamedDecl *Ctx;
2493
2494 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2495 : Info(Info), Ctx(Ctx) {}
2496
2497 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2498 switch (TL.getTypeLocClass()) {
2499#define ABSTRACT_TYPELOC(CLASS, PARENT)
2500#define TYPELOC(CLASS, PARENT) \
2501 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2502#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002503 }
John McCall94c3b562010-08-18 09:41:07 +00002504 }
Mike Stump1eb44332009-09-09 15:08:12 +00002505
John McCall94c3b562010-08-18 09:41:07 +00002506 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2507 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2508 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2509 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2510 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002511 }
John McCall94c3b562010-08-18 09:41:07 +00002512 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002513
John McCall94c3b562010-08-18 09:41:07 +00002514 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2515 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2516 }
Mike Stump1eb44332009-09-09 15:08:12 +00002517
John McCall94c3b562010-08-18 09:41:07 +00002518 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2519 // Visit the type parameters from a permissive context.
2520 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2521 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2522 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2523 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2524 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2525 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002526 }
John McCall94c3b562010-08-18 09:41:07 +00002527 }
Mike Stump1eb44332009-09-09 15:08:12 +00002528
John McCall94c3b562010-08-18 09:41:07 +00002529 // Visit pointee types from a permissive context.
2530#define CheckPolymorphic(Type) \
2531 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2532 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2533 }
2534 CheckPolymorphic(PointerTypeLoc)
2535 CheckPolymorphic(ReferenceTypeLoc)
2536 CheckPolymorphic(MemberPointerTypeLoc)
2537 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002538
John McCall94c3b562010-08-18 09:41:07 +00002539 /// Handle all the types we haven't given a more specific
2540 /// implementation for above.
2541 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2542 // Every other kind of type that we haven't called out already
2543 // that has an inner type is either (1) sugar or (2) contains that
2544 // inner type in some way as a subobject.
2545 if (TypeLoc Next = TL.getNextTypeLoc())
2546 return Visit(Next, Sel);
2547
2548 // If there's no inner type and we're in a permissive context,
2549 // don't diagnose.
2550 if (Sel == Sema::AbstractNone) return;
2551
2552 // Check whether the type matches the abstract type.
2553 QualType T = TL.getType();
2554 if (T->isArrayType()) {
2555 Sel = Sema::AbstractArrayType;
2556 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002557 }
John McCall94c3b562010-08-18 09:41:07 +00002558 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2559 if (CT != Info.AbstractType) return;
2560
2561 // It matched; do some magic.
2562 if (Sel == Sema::AbstractArrayType) {
2563 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2564 << T << TL.getSourceRange();
2565 } else {
2566 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2567 << Sel << T << TL.getSourceRange();
2568 }
2569 Info.DiagnoseAbstractType();
2570 }
2571};
2572
2573void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2574 Sema::AbstractDiagSelID Sel) {
2575 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2576}
2577
2578}
2579
2580/// Check for invalid uses of an abstract type in a method declaration.
2581static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2582 CXXMethodDecl *MD) {
2583 // No need to do the check on definitions, which require that
2584 // the return/param types be complete.
2585 if (MD->isThisDeclarationADefinition())
2586 return;
2587
2588 // For safety's sake, just ignore it if we don't have type source
2589 // information. This should never happen for non-implicit methods,
2590 // but...
2591 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2592 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2593}
2594
2595/// Check for invalid uses of an abstract type within a class definition.
2596static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2597 CXXRecordDecl *RD) {
2598 for (CXXRecordDecl::decl_iterator
2599 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2600 Decl *D = *I;
2601 if (D->isImplicit()) continue;
2602
2603 // Methods and method templates.
2604 if (isa<CXXMethodDecl>(D)) {
2605 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2606 } else if (isa<FunctionTemplateDecl>(D)) {
2607 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2608 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2609
2610 // Fields and static variables.
2611 } else if (isa<FieldDecl>(D)) {
2612 FieldDecl *FD = cast<FieldDecl>(D);
2613 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2614 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2615 } else if (isa<VarDecl>(D)) {
2616 VarDecl *VD = cast<VarDecl>(D);
2617 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2618 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2619
2620 // Nested classes and class templates.
2621 } else if (isa<CXXRecordDecl>(D)) {
2622 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2623 } else if (isa<ClassTemplateDecl>(D)) {
2624 CheckAbstractClassUsage(Info,
2625 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2626 }
2627 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002628}
2629
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002630/// \brief Perform semantic checks on a class definition that has been
2631/// completing, introducing implicitly-declared members, checking for
2632/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002633void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002634 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002635 return;
2636
John McCall94c3b562010-08-18 09:41:07 +00002637 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2638 AbstractUsageInfo Info(*this, Record);
2639 CheckAbstractClassUsage(Info, Record);
2640 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002641
2642 // If this is not an aggregate type and has no user-declared constructor,
2643 // complain about any non-static data members of reference or const scalar
2644 // type, since they will never get initializers.
2645 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2646 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2647 bool Complained = false;
2648 for (RecordDecl::field_iterator F = Record->field_begin(),
2649 FEnd = Record->field_end();
2650 F != FEnd; ++F) {
2651 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002652 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002653 if (!Complained) {
2654 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2655 << Record->getTagKind() << Record;
2656 Complained = true;
2657 }
2658
2659 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2660 << F->getType()->isReferenceType()
2661 << F->getDeclName();
2662 }
2663 }
2664 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002665
2666 if (Record->isDynamicClass())
2667 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002668
2669 if (Record->getIdentifier()) {
2670 // C++ [class.mem]p13:
2671 // If T is the name of a class, then each of the following shall have a
2672 // name different from T:
2673 // - every member of every anonymous union that is a member of class T.
2674 //
2675 // C++ [class.mem]p14:
2676 // In addition, if class T has a user-declared constructor (12.1), every
2677 // non-static data member of class T shall have a name different from T.
2678 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002679 R.first != R.second; ++R.first) {
2680 NamedDecl *D = *R.first;
2681 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2682 isa<IndirectFieldDecl>(D)) {
2683 Diag(D->getLocation(), diag::err_member_name_of_class)
2684 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002685 break;
2686 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002687 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002688 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002689}
2690
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002691void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002692 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002693 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002694 SourceLocation RBrac,
2695 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002696 if (!TagDecl)
2697 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregor42af25f2009-05-11 19:58:34 +00002699 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002700
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002701 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002702 // strict aliasing violation!
2703 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002704 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002705
Douglas Gregor23c94db2010-07-02 17:43:08 +00002706 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002707 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002708}
2709
Douglas Gregord92ec472010-07-01 05:10:53 +00002710namespace {
2711 /// \brief Helper class that collects exception specifications for
2712 /// implicitly-declared special member functions.
2713 class ImplicitExceptionSpecification {
2714 ASTContext &Context;
2715 bool AllowsAllExceptions;
2716 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2717 llvm::SmallVector<QualType, 4> Exceptions;
2718
2719 public:
2720 explicit ImplicitExceptionSpecification(ASTContext &Context)
2721 : Context(Context), AllowsAllExceptions(false) { }
2722
2723 /// \brief Whether the special member function should have any
2724 /// exception specification at all.
2725 bool hasExceptionSpecification() const {
2726 return !AllowsAllExceptions;
2727 }
2728
2729 /// \brief Whether the special member function should have a
2730 /// throw(...) exception specification (a Microsoft extension).
2731 bool hasAnyExceptionSpecification() const {
2732 return false;
2733 }
2734
2735 /// \brief The number of exceptions in the exception specification.
2736 unsigned size() const { return Exceptions.size(); }
2737
2738 /// \brief The set of exceptions in the exception specification.
2739 const QualType *data() const { return Exceptions.data(); }
2740
2741 /// \brief Note that
2742 void CalledDecl(CXXMethodDecl *Method) {
2743 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002744 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002745 return;
2746
2747 const FunctionProtoType *Proto
2748 = Method->getType()->getAs<FunctionProtoType>();
2749
2750 // If this function can throw any exceptions, make a note of that.
2751 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2752 AllowsAllExceptions = true;
2753 ExceptionsSeen.clear();
2754 Exceptions.clear();
2755 return;
2756 }
2757
2758 // Record the exceptions in this function's exception specification.
2759 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2760 EEnd = Proto->exception_end();
2761 E != EEnd; ++E)
2762 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2763 Exceptions.push_back(*E);
2764 }
2765 };
2766}
2767
2768
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002769/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2770/// special functions, such as the default constructor, copy
2771/// constructor, or destructor, to the given C++ class (C++
2772/// [special]p1). This routine can only be executed just before the
2773/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002774void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002775 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002776 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002777
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002778 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002779 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002780
Douglas Gregora376d102010-07-02 21:50:04 +00002781 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2782 ++ASTContext::NumImplicitCopyAssignmentOperators;
2783
2784 // If we have a dynamic class, then the copy assignment operator may be
2785 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2786 // it shows up in the right place in the vtable and that we diagnose
2787 // problems with the implicit exception specification.
2788 if (ClassDecl->isDynamicClass())
2789 DeclareImplicitCopyAssignment(ClassDecl);
2790 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002791
Douglas Gregor4923aa22010-07-02 20:37:36 +00002792 if (!ClassDecl->hasUserDeclaredDestructor()) {
2793 ++ASTContext::NumImplicitDestructors;
2794
2795 // If we have a dynamic class, then the destructor may be virtual, so we
2796 // have to declare the destructor immediately. This ensures that, e.g., it
2797 // shows up in the right place in the vtable and that we diagnose problems
2798 // with the implicit exception specification.
2799 if (ClassDecl->isDynamicClass())
2800 DeclareImplicitDestructor(ClassDecl);
2801 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002802}
2803
John McCalld226f652010-08-21 09:40:31 +00002804void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002805 if (!D)
2806 return;
2807
2808 TemplateParameterList *Params = 0;
2809 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2810 Params = Template->getTemplateParameters();
2811 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2812 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2813 Params = PartialSpec->getTemplateParameters();
2814 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002815 return;
2816
Douglas Gregor6569d682009-05-27 23:11:45 +00002817 for (TemplateParameterList::iterator Param = Params->begin(),
2818 ParamEnd = Params->end();
2819 Param != ParamEnd; ++Param) {
2820 NamedDecl *Named = cast<NamedDecl>(*Param);
2821 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002822 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002823 IdResolver.AddDecl(Named);
2824 }
2825 }
2826}
2827
John McCalld226f652010-08-21 09:40:31 +00002828void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002829 if (!RecordD) return;
2830 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002831 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002832 PushDeclContext(S, Record);
2833}
2834
John McCalld226f652010-08-21 09:40:31 +00002835void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002836 if (!RecordD) return;
2837 PopDeclContext();
2838}
2839
Douglas Gregor72b505b2008-12-16 21:30:33 +00002840/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2841/// parsing a top-level (non-nested) C++ class, and we are now
2842/// parsing those parts of the given Method declaration that could
2843/// not be parsed earlier (C++ [class.mem]p2), such as default
2844/// arguments. This action should enter the scope of the given
2845/// Method declaration as if we had just parsed the qualified method
2846/// name. However, it should not bring the parameters into scope;
2847/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002848void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002849}
2850
2851/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2852/// C++ method declaration. We're (re-)introducing the given
2853/// function parameter into scope for use in parsing later parts of
2854/// the method declaration. For example, we could see an
2855/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002856void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002857 if (!ParamD)
2858 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002859
John McCalld226f652010-08-21 09:40:31 +00002860 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002861
2862 // If this parameter has an unparsed default argument, clear it out
2863 // to make way for the parsed default argument.
2864 if (Param->hasUnparsedDefaultArg())
2865 Param->setDefaultArg(0);
2866
John McCalld226f652010-08-21 09:40:31 +00002867 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002868 if (Param->getDeclName())
2869 IdResolver.AddDecl(Param);
2870}
2871
2872/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2873/// processing the delayed method declaration for Method. The method
2874/// declaration is now considered finished. There may be a separate
2875/// ActOnStartOfFunctionDef action later (not necessarily
2876/// immediately!) for this method, if it was also defined inside the
2877/// class body.
John McCalld226f652010-08-21 09:40:31 +00002878void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002879 if (!MethodD)
2880 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002882 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002883
John McCalld226f652010-08-21 09:40:31 +00002884 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002885
2886 // Now that we have our default arguments, check the constructor
2887 // again. It could produce additional diagnostics or affect whether
2888 // the class has implicitly-declared destructors, among other
2889 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002890 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2891 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002892
2893 // Check the default arguments, which we may have added.
2894 if (!Method->isInvalidDecl())
2895 CheckCXXDefaultArguments(Method);
2896}
2897
Douglas Gregor42a552f2008-11-05 20:51:48 +00002898/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002899/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002900/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002901/// emit diagnostics and set the invalid bit to true. In any case, the type
2902/// will be updated to reflect a well-formed type for the constructor and
2903/// returned.
2904QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002905 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002906 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002907
2908 // C++ [class.ctor]p3:
2909 // A constructor shall not be virtual (10.3) or static (9.4). A
2910 // constructor can be invoked for a const, volatile or const
2911 // volatile object. A constructor shall not be declared const,
2912 // volatile, or const volatile (9.3.2).
2913 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002914 if (!D.isInvalidType())
2915 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2916 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2917 << SourceRange(D.getIdentifierLoc());
2918 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002919 }
John McCalld931b082010-08-26 03:08:43 +00002920 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002921 if (!D.isInvalidType())
2922 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2923 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2924 << SourceRange(D.getIdentifierLoc());
2925 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002926 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002927 }
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002929 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00002930 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002931 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002932 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2933 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002934 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002935 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2936 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002937 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002938 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2939 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00002940 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002941 }
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Douglas Gregor42a552f2008-11-05 20:51:48 +00002943 // Rebuild the function type "R" without any type qualifiers (in
2944 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002945 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002946 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00002947 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2948 return R;
2949
2950 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2951 EPI.TypeQuals = 0;
2952
Chris Lattner65401802009-04-25 08:28:21 +00002953 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00002954 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002955}
2956
Douglas Gregor72b505b2008-12-16 21:30:33 +00002957/// CheckConstructor - Checks a fully-formed constructor for
2958/// well-formedness, issuing any diagnostics required. Returns true if
2959/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002960void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002961 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002962 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2963 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002964 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002965
2966 // C++ [class.copy]p3:
2967 // A declaration of a constructor for a class X is ill-formed if
2968 // its first parameter is of type (optionally cv-qualified) X and
2969 // either there are no other parameters or else all other
2970 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002971 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002972 ((Constructor->getNumParams() == 1) ||
2973 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002974 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2975 Constructor->getTemplateSpecializationKind()
2976 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002977 QualType ParamType = Constructor->getParamDecl(0)->getType();
2978 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2979 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002980 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002981 const char *ConstRef
2982 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2983 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002984 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002985 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002986
2987 // FIXME: Rather that making the constructor invalid, we should endeavor
2988 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002989 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002990 }
2991 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002992}
2993
John McCall15442822010-08-04 01:04:25 +00002994/// CheckDestructor - Checks a fully-formed destructor definition for
2995/// well-formedness, issuing any diagnostics required. Returns true
2996/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002997bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002998 CXXRecordDecl *RD = Destructor->getParent();
2999
3000 if (Destructor->isVirtual()) {
3001 SourceLocation Loc;
3002
3003 if (!Destructor->isImplicit())
3004 Loc = Destructor->getLocation();
3005 else
3006 Loc = RD->getLocation();
3007
3008 // If we have a virtual destructor, look up the deallocation function
3009 FunctionDecl *OperatorDelete = 0;
3010 DeclarationName Name =
3011 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003012 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003013 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003014
3015 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003016
3017 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003018 }
Anders Carlsson37909802009-11-30 21:24:50 +00003019
3020 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003021}
3022
Mike Stump1eb44332009-09-09 15:08:12 +00003023static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003024FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3025 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3026 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003027 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003028}
3029
Douglas Gregor42a552f2008-11-05 20:51:48 +00003030/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3031/// the well-formednes of the destructor declarator @p D with type @p
3032/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003033/// emit diagnostics and set the declarator to invalid. Even if this happens,
3034/// will be updated to reflect a well-formed type for the destructor and
3035/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003036QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003037 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003038 // C++ [class.dtor]p1:
3039 // [...] A typedef-name that names a class is a class-name
3040 // (7.1.3); however, a typedef-name that names a class shall not
3041 // be used as the identifier in the declarator for a destructor
3042 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003043 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003044 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003045 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003046 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003047
3048 // C++ [class.dtor]p2:
3049 // A destructor is used to destroy objects of its class type. A
3050 // destructor takes no parameters, and no return type can be
3051 // specified for it (not even void). The address of a destructor
3052 // shall not be taken. A destructor shall not be static. A
3053 // destructor can be invoked for a const, volatile or const
3054 // volatile object. A destructor shall not be declared const,
3055 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003056 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003057 if (!D.isInvalidType())
3058 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3059 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003060 << SourceRange(D.getIdentifierLoc())
3061 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3062
John McCalld931b082010-08-26 03:08:43 +00003063 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003064 }
Chris Lattner65401802009-04-25 08:28:21 +00003065 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003066 // Destructors don't have return types, but the parser will
3067 // happily parse something like:
3068 //
3069 // class X {
3070 // float ~X();
3071 // };
3072 //
3073 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003074 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3075 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3076 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003077 }
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003079 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003080 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003081 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3083 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003084 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003085 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3086 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003087 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003088 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3089 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003090 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003091 }
3092
3093 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003094 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003095 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3096
3097 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003098 FTI.freeArgs();
3099 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003100 }
3101
Mike Stump1eb44332009-09-09 15:08:12 +00003102 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003103 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003104 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003105 D.setInvalidType();
3106 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003107
3108 // Rebuild the function type "R" without any type qualifiers or
3109 // parameters (in case any of the errors above fired) and with
3110 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003111 // types.
John McCalle23cf432010-12-14 08:05:40 +00003112 if (!D.isInvalidType())
3113 return R;
3114
Douglas Gregord92ec472010-07-01 05:10:53 +00003115 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003116 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3117 EPI.Variadic = false;
3118 EPI.TypeQuals = 0;
3119 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003120}
3121
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003122/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3123/// well-formednes of the conversion function declarator @p D with
3124/// type @p R. If there are any errors in the declarator, this routine
3125/// will emit diagnostics and return true. Otherwise, it will return
3126/// false. Either way, the type @p R will be updated to reflect a
3127/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003128void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003129 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003130 // C++ [class.conv.fct]p1:
3131 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003132 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003133 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003134 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003135 if (!D.isInvalidType())
3136 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3137 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3138 << SourceRange(D.getIdentifierLoc());
3139 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003140 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003141 }
John McCalla3f81372010-04-13 00:04:31 +00003142
3143 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3144
Chris Lattner6e475012009-04-25 08:35:12 +00003145 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003146 // Conversion functions don't have return types, but the parser will
3147 // happily parse something like:
3148 //
3149 // class X {
3150 // float operator bool();
3151 // };
3152 //
3153 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003154 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3155 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3156 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003157 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003158 }
3159
John McCalla3f81372010-04-13 00:04:31 +00003160 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3161
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003162 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003163 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003164 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3165
3166 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003167 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003168 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003169 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003170 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003171 D.setInvalidType();
3172 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003173
John McCalla3f81372010-04-13 00:04:31 +00003174 // Diagnose "&operator bool()" and other such nonsense. This
3175 // is actually a gcc extension which we don't support.
3176 if (Proto->getResultType() != ConvType) {
3177 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3178 << Proto->getResultType();
3179 D.setInvalidType();
3180 ConvType = Proto->getResultType();
3181 }
3182
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003183 // C++ [class.conv.fct]p4:
3184 // The conversion-type-id shall not represent a function type nor
3185 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003186 if (ConvType->isArrayType()) {
3187 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3188 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003189 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003190 } else if (ConvType->isFunctionType()) {
3191 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3192 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003193 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003194 }
3195
3196 // Rebuild the function type "R" without any parameters (in case any
3197 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003198 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003199 if (D.isInvalidType())
3200 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003201
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003202 // C++0x explicit conversion operators.
3203 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003204 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003205 diag::warn_explicit_conversion_functions)
3206 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003207}
3208
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003209/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3210/// the declaration of the given C++ conversion function. This routine
3211/// is responsible for recording the conversion function in the C++
3212/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003213Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003214 assert(Conversion && "Expected to receive a conversion function declaration");
3215
Douglas Gregor9d350972008-12-12 08:25:50 +00003216 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003217
3218 // Make sure we aren't redeclaring the conversion function.
3219 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003220
3221 // C++ [class.conv.fct]p1:
3222 // [...] A conversion function is never used to convert a
3223 // (possibly cv-qualified) object to the (possibly cv-qualified)
3224 // same object type (or a reference to it), to a (possibly
3225 // cv-qualified) base class of that type (or a reference to it),
3226 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003227 // FIXME: Suppress this warning if the conversion function ends up being a
3228 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003229 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003230 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003231 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003232 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003233 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3234 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003235 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003236 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003237 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3238 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003239 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003240 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003241 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003242 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003243 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003244 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003245 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003246 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003247 }
3248
Douglas Gregore80622f2010-09-29 04:25:11 +00003249 if (FunctionTemplateDecl *ConversionTemplate
3250 = Conversion->getDescribedFunctionTemplate())
3251 return ConversionTemplate;
3252
John McCalld226f652010-08-21 09:40:31 +00003253 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003254}
3255
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003256//===----------------------------------------------------------------------===//
3257// Namespace Handling
3258//===----------------------------------------------------------------------===//
3259
John McCallea318642010-08-26 09:15:37 +00003260
3261
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003262/// ActOnStartNamespaceDef - This is called at the start of a namespace
3263/// definition.
John McCalld226f652010-08-21 09:40:31 +00003264Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003265 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003266 SourceLocation IdentLoc,
3267 IdentifierInfo *II,
3268 SourceLocation LBrace,
3269 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003270 // anonymous namespace starts at its left brace
3271 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3272 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003273 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003274 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003275
3276 Scope *DeclRegionScope = NamespcScope->getParent();
3277
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003278 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3279
John McCall90f14502010-12-10 02:59:44 +00003280 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3281 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003282
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003283 if (II) {
3284 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003285 // The identifier in an original-namespace-definition shall not
3286 // have been previously defined in the declarative region in
3287 // which the original-namespace-definition appears. The
3288 // identifier in an original-namespace-definition is the name of
3289 // the namespace. Subsequently in that declarative region, it is
3290 // treated as an original-namespace-name.
3291 //
3292 // Since namespace names are unique in their scope, and we don't
3293 // look through using directives, just
3294 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3295 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Douglas Gregor44b43212008-12-11 16:49:14 +00003297 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3298 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003299 if (Namespc->isInline() != OrigNS->isInline()) {
3300 // inline-ness must match
3301 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3302 << Namespc->isInline();
3303 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3304 Namespc->setInvalidDecl();
3305 // Recover by ignoring the new namespace's inline status.
3306 Namespc->setInline(OrigNS->isInline());
3307 }
3308
Douglas Gregor44b43212008-12-11 16:49:14 +00003309 // Attach this namespace decl to the chain of extended namespace
3310 // definitions.
3311 OrigNS->setNextNamespace(Namespc);
3312 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003313
Mike Stump1eb44332009-09-09 15:08:12 +00003314 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003315 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003316 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003317 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003318 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003319 } else if (PrevDecl) {
3320 // This is an invalid name redefinition.
3321 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3322 << Namespc->getDeclName();
3323 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3324 Namespc->setInvalidDecl();
3325 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003326 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003327 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003328 // This is the first "real" definition of the namespace "std", so update
3329 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003330 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003331 // We had already defined a dummy namespace "std". Link this new
3332 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003333 StdNS->setNextNamespace(Namespc);
3334 StdNS->setLocation(IdentLoc);
3335 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003336 }
3337
3338 // Make our StdNamespace cache point at the first real definition of the
3339 // "std" namespace.
3340 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003341 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003342
3343 PushOnScopeChains(Namespc, DeclRegionScope);
3344 } else {
John McCall9aeed322009-10-01 00:25:31 +00003345 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003346 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003347
3348 // Link the anonymous namespace into its parent.
3349 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003350 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003351 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3352 PrevDecl = TU->getAnonymousNamespace();
3353 TU->setAnonymousNamespace(Namespc);
3354 } else {
3355 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3356 PrevDecl = ND->getAnonymousNamespace();
3357 ND->setAnonymousNamespace(Namespc);
3358 }
3359
3360 // Link the anonymous namespace with its previous declaration.
3361 if (PrevDecl) {
3362 assert(PrevDecl->isAnonymousNamespace());
3363 assert(!PrevDecl->getNextNamespace());
3364 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3365 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003366
3367 if (Namespc->isInline() != PrevDecl->isInline()) {
3368 // inline-ness must match
3369 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3370 << Namespc->isInline();
3371 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3372 Namespc->setInvalidDecl();
3373 // Recover by ignoring the new namespace's inline status.
3374 Namespc->setInline(PrevDecl->isInline());
3375 }
John McCall5fdd7642009-12-16 02:06:49 +00003376 }
John McCall9aeed322009-10-01 00:25:31 +00003377
Douglas Gregora4181472010-03-24 00:46:35 +00003378 CurContext->addDecl(Namespc);
3379
John McCall9aeed322009-10-01 00:25:31 +00003380 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3381 // behaves as if it were replaced by
3382 // namespace unique { /* empty body */ }
3383 // using namespace unique;
3384 // namespace unique { namespace-body }
3385 // where all occurrences of 'unique' in a translation unit are
3386 // replaced by the same identifier and this identifier differs
3387 // from all other identifiers in the entire program.
3388
3389 // We just create the namespace with an empty name and then add an
3390 // implicit using declaration, just like the standard suggests.
3391 //
3392 // CodeGen enforces the "universally unique" aspect by giving all
3393 // declarations semantically contained within an anonymous
3394 // namespace internal linkage.
3395
John McCall5fdd7642009-12-16 02:06:49 +00003396 if (!PrevDecl) {
3397 UsingDirectiveDecl* UD
3398 = UsingDirectiveDecl::Create(Context, CurContext,
3399 /* 'using' */ LBrace,
3400 /* 'namespace' */ SourceLocation(),
3401 /* qualifier */ SourceRange(),
3402 /* NNS */ NULL,
3403 /* identifier */ SourceLocation(),
3404 Namespc,
3405 /* Ancestor */ CurContext);
3406 UD->setImplicit();
3407 CurContext->addDecl(UD);
3408 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003409 }
3410
3411 // Although we could have an invalid decl (i.e. the namespace name is a
3412 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003413 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3414 // for the namespace has the declarations that showed up in that particular
3415 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003416 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003417 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003418}
3419
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003420/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3421/// is a namespace alias, returns the namespace it points to.
3422static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3423 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3424 return AD->getNamespace();
3425 return dyn_cast_or_null<NamespaceDecl>(D);
3426}
3427
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003428/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3429/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003430void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003431 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3432 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3433 Namespc->setRBracLoc(RBrace);
3434 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003435 if (Namespc->hasAttr<VisibilityAttr>())
3436 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003437}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003438
John McCall384aff82010-08-25 07:42:41 +00003439CXXRecordDecl *Sema::getStdBadAlloc() const {
3440 return cast_or_null<CXXRecordDecl>(
3441 StdBadAlloc.get(Context.getExternalSource()));
3442}
3443
3444NamespaceDecl *Sema::getStdNamespace() const {
3445 return cast_or_null<NamespaceDecl>(
3446 StdNamespace.get(Context.getExternalSource()));
3447}
3448
Douglas Gregor66992202010-06-29 17:53:46 +00003449/// \brief Retrieve the special "std" namespace, which may require us to
3450/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003451NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003452 if (!StdNamespace) {
3453 // The "std" namespace has not yet been defined, so build one implicitly.
3454 StdNamespace = NamespaceDecl::Create(Context,
3455 Context.getTranslationUnitDecl(),
3456 SourceLocation(),
3457 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003458 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003459 }
3460
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003461 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003462}
3463
John McCalld226f652010-08-21 09:40:31 +00003464Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003465 SourceLocation UsingLoc,
3466 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003467 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003468 SourceLocation IdentLoc,
3469 IdentifierInfo *NamespcName,
3470 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003471 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3472 assert(NamespcName && "Invalid NamespcName.");
3473 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003474
3475 // This can only happen along a recovery path.
3476 while (S->getFlags() & Scope::TemplateParamScope)
3477 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003478 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003479
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003480 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003481 NestedNameSpecifier *Qualifier = 0;
3482 if (SS.isSet())
3483 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3484
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003485 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003486 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3487 LookupParsedName(R, S, &SS);
3488 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003489 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003490
Douglas Gregor66992202010-06-29 17:53:46 +00003491 if (R.empty()) {
3492 // Allow "using namespace std;" or "using namespace ::std;" even if
3493 // "std" hasn't been defined yet, for GCC compatibility.
3494 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3495 NamespcName->isStr("std")) {
3496 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003497 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003498 R.resolveKind();
3499 }
3500 // Otherwise, attempt typo correction.
3501 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3502 CTC_NoKeywords, 0)) {
3503 if (R.getAsSingle<NamespaceDecl>() ||
3504 R.getAsSingle<NamespaceAliasDecl>()) {
3505 if (DeclContext *DC = computeDeclContext(SS, false))
3506 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3507 << NamespcName << DC << Corrected << SS.getRange()
3508 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3509 else
3510 Diag(IdentLoc, diag::err_using_directive_suggest)
3511 << NamespcName << Corrected
3512 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3513 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3514 << Corrected;
3515
3516 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003517 } else {
3518 R.clear();
3519 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003520 }
3521 }
3522 }
3523
John McCallf36e02d2009-10-09 21:13:30 +00003524 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003525 NamedDecl *Named = R.getFoundDecl();
3526 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3527 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003528 // C++ [namespace.udir]p1:
3529 // A using-directive specifies that the names in the nominated
3530 // namespace can be used in the scope in which the
3531 // using-directive appears after the using-directive. During
3532 // unqualified name lookup (3.4.1), the names appear as if they
3533 // were declared in the nearest enclosing namespace which
3534 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003535 // namespace. [Note: in this context, "contains" means "contains
3536 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003537
3538 // Find enclosing context containing both using-directive and
3539 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003540 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003541 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3542 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3543 CommonAncestor = CommonAncestor->getParent();
3544
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003545 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003546 SS.getRange(),
3547 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003548 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003549 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003550 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003551 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003552 }
3553
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003554 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003555 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003556}
3557
3558void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3559 // If scope has associated entity, then using directive is at namespace
3560 // or translation unit scope. We add UsingDirectiveDecls, into
3561 // it's lookup structure.
3562 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003563 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003564 else
3565 // Otherwise it is block-sope. using-directives will affect lookup
3566 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003567 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003568}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003569
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003570
John McCalld226f652010-08-21 09:40:31 +00003571Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003572 AccessSpecifier AS,
3573 bool HasUsingKeyword,
3574 SourceLocation UsingLoc,
3575 CXXScopeSpec &SS,
3576 UnqualifiedId &Name,
3577 AttributeList *AttrList,
3578 bool IsTypeName,
3579 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003580 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Douglas Gregor12c118a2009-11-04 16:30:06 +00003582 switch (Name.getKind()) {
3583 case UnqualifiedId::IK_Identifier:
3584 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003585 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003586 case UnqualifiedId::IK_ConversionFunctionId:
3587 break;
3588
3589 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003590 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003591 // C++0x inherited constructors.
3592 if (getLangOptions().CPlusPlus0x) break;
3593
Douglas Gregor12c118a2009-11-04 16:30:06 +00003594 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3595 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003596 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003597
3598 case UnqualifiedId::IK_DestructorName:
3599 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3600 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003601 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003602
3603 case UnqualifiedId::IK_TemplateId:
3604 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3605 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003606 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003607 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003608
3609 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3610 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003611 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003612 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003613
John McCall60fa3cf2009-12-11 02:10:03 +00003614 // Warn about using declarations.
3615 // TODO: store that the declaration was written without 'using' and
3616 // talk about access decls instead of using decls in the
3617 // diagnostics.
3618 if (!HasUsingKeyword) {
3619 UsingLoc = Name.getSourceRange().getBegin();
3620
3621 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003622 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003623 }
3624
Douglas Gregor56c04582010-12-16 00:46:58 +00003625 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3626 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3627 return 0;
3628
John McCall9488ea12009-11-17 05:59:44 +00003629 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003630 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003631 /* IsInstantiation */ false,
3632 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003633 if (UD)
3634 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003635
John McCalld226f652010-08-21 09:40:31 +00003636 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003637}
3638
Douglas Gregor09acc982010-07-07 23:08:52 +00003639/// \brief Determine whether a using declaration considers the given
3640/// declarations as "equivalent", e.g., if they are redeclarations of
3641/// the same entity or are both typedefs of the same type.
3642static bool
3643IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3644 bool &SuppressRedeclaration) {
3645 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3646 SuppressRedeclaration = false;
3647 return true;
3648 }
3649
3650 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3651 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3652 SuppressRedeclaration = true;
3653 return Context.hasSameType(TD1->getUnderlyingType(),
3654 TD2->getUnderlyingType());
3655 }
3656
3657 return false;
3658}
3659
3660
John McCall9f54ad42009-12-10 09:41:52 +00003661/// Determines whether to create a using shadow decl for a particular
3662/// decl, given the set of decls existing prior to this using lookup.
3663bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3664 const LookupResult &Previous) {
3665 // Diagnose finding a decl which is not from a base class of the
3666 // current class. We do this now because there are cases where this
3667 // function will silently decide not to build a shadow decl, which
3668 // will pre-empt further diagnostics.
3669 //
3670 // We don't need to do this in C++0x because we do the check once on
3671 // the qualifier.
3672 //
3673 // FIXME: diagnose the following if we care enough:
3674 // struct A { int foo; };
3675 // struct B : A { using A::foo; };
3676 // template <class T> struct C : A {};
3677 // template <class T> struct D : C<T> { using B::foo; } // <---
3678 // This is invalid (during instantiation) in C++03 because B::foo
3679 // resolves to the using decl in B, which is not a base class of D<T>.
3680 // We can't diagnose it immediately because C<T> is an unknown
3681 // specialization. The UsingShadowDecl in D<T> then points directly
3682 // to A::foo, which will look well-formed when we instantiate.
3683 // The right solution is to not collapse the shadow-decl chain.
3684 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3685 DeclContext *OrigDC = Orig->getDeclContext();
3686
3687 // Handle enums and anonymous structs.
3688 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3689 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3690 while (OrigRec->isAnonymousStructOrUnion())
3691 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3692
3693 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3694 if (OrigDC == CurContext) {
3695 Diag(Using->getLocation(),
3696 diag::err_using_decl_nested_name_specifier_is_current_class)
3697 << Using->getNestedNameRange();
3698 Diag(Orig->getLocation(), diag::note_using_decl_target);
3699 return true;
3700 }
3701
3702 Diag(Using->getNestedNameRange().getBegin(),
3703 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3704 << Using->getTargetNestedNameDecl()
3705 << cast<CXXRecordDecl>(CurContext)
3706 << Using->getNestedNameRange();
3707 Diag(Orig->getLocation(), diag::note_using_decl_target);
3708 return true;
3709 }
3710 }
3711
3712 if (Previous.empty()) return false;
3713
3714 NamedDecl *Target = Orig;
3715 if (isa<UsingShadowDecl>(Target))
3716 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3717
John McCalld7533ec2009-12-11 02:33:26 +00003718 // If the target happens to be one of the previous declarations, we
3719 // don't have a conflict.
3720 //
3721 // FIXME: but we might be increasing its access, in which case we
3722 // should redeclare it.
3723 NamedDecl *NonTag = 0, *Tag = 0;
3724 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3725 I != E; ++I) {
3726 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003727 bool Result;
3728 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3729 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003730
3731 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3732 }
3733
John McCall9f54ad42009-12-10 09:41:52 +00003734 if (Target->isFunctionOrFunctionTemplate()) {
3735 FunctionDecl *FD;
3736 if (isa<FunctionTemplateDecl>(Target))
3737 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3738 else
3739 FD = cast<FunctionDecl>(Target);
3740
3741 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003742 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003743 case Ovl_Overload:
3744 return false;
3745
3746 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003747 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003748 break;
3749
3750 // We found a decl with the exact signature.
3751 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003752 // If we're in a record, we want to hide the target, so we
3753 // return true (without a diagnostic) to tell the caller not to
3754 // build a shadow decl.
3755 if (CurContext->isRecord())
3756 return true;
3757
3758 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003759 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003760 break;
3761 }
3762
3763 Diag(Target->getLocation(), diag::note_using_decl_target);
3764 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3765 return true;
3766 }
3767
3768 // Target is not a function.
3769
John McCall9f54ad42009-12-10 09:41:52 +00003770 if (isa<TagDecl>(Target)) {
3771 // No conflict between a tag and a non-tag.
3772 if (!Tag) return false;
3773
John McCall41ce66f2009-12-10 19:51:03 +00003774 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003775 Diag(Target->getLocation(), diag::note_using_decl_target);
3776 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3777 return true;
3778 }
3779
3780 // No conflict between a tag and a non-tag.
3781 if (!NonTag) return false;
3782
John McCall41ce66f2009-12-10 19:51:03 +00003783 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003784 Diag(Target->getLocation(), diag::note_using_decl_target);
3785 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3786 return true;
3787}
3788
John McCall9488ea12009-11-17 05:59:44 +00003789/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003790UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003791 UsingDecl *UD,
3792 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003793
3794 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003795 NamedDecl *Target = Orig;
3796 if (isa<UsingShadowDecl>(Target)) {
3797 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3798 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003799 }
3800
3801 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003802 = UsingShadowDecl::Create(Context, CurContext,
3803 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003804 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003805
3806 Shadow->setAccess(UD->getAccess());
3807 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3808 Shadow->setInvalidDecl();
3809
John McCall9488ea12009-11-17 05:59:44 +00003810 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003811 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003812 else
John McCall604e7f12009-12-08 07:46:18 +00003813 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003814
John McCall604e7f12009-12-08 07:46:18 +00003815
John McCall9f54ad42009-12-10 09:41:52 +00003816 return Shadow;
3817}
John McCall604e7f12009-12-08 07:46:18 +00003818
John McCall9f54ad42009-12-10 09:41:52 +00003819/// Hides a using shadow declaration. This is required by the current
3820/// using-decl implementation when a resolvable using declaration in a
3821/// class is followed by a declaration which would hide or override
3822/// one or more of the using decl's targets; for example:
3823///
3824/// struct Base { void foo(int); };
3825/// struct Derived : Base {
3826/// using Base::foo;
3827/// void foo(int);
3828/// };
3829///
3830/// The governing language is C++03 [namespace.udecl]p12:
3831///
3832/// When a using-declaration brings names from a base class into a
3833/// derived class scope, member functions in the derived class
3834/// override and/or hide member functions with the same name and
3835/// parameter types in a base class (rather than conflicting).
3836///
3837/// There are two ways to implement this:
3838/// (1) optimistically create shadow decls when they're not hidden
3839/// by existing declarations, or
3840/// (2) don't create any shadow decls (or at least don't make them
3841/// visible) until we've fully parsed/instantiated the class.
3842/// The problem with (1) is that we might have to retroactively remove
3843/// a shadow decl, which requires several O(n) operations because the
3844/// decl structures are (very reasonably) not designed for removal.
3845/// (2) avoids this but is very fiddly and phase-dependent.
3846void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003847 if (Shadow->getDeclName().getNameKind() ==
3848 DeclarationName::CXXConversionFunctionName)
3849 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3850
John McCall9f54ad42009-12-10 09:41:52 +00003851 // Remove it from the DeclContext...
3852 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003853
John McCall9f54ad42009-12-10 09:41:52 +00003854 // ...and the scope, if applicable...
3855 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003856 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003857 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003858 }
3859
John McCall9f54ad42009-12-10 09:41:52 +00003860 // ...and the using decl.
3861 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3862
3863 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003864 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003865}
3866
John McCall7ba107a2009-11-18 02:36:19 +00003867/// Builds a using declaration.
3868///
3869/// \param IsInstantiation - Whether this call arises from an
3870/// instantiation of an unresolved using declaration. We treat
3871/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003872NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3873 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003874 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003875 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003876 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003877 bool IsInstantiation,
3878 bool IsTypeName,
3879 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003880 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003881 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003882 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003883
Anders Carlsson550b14b2009-08-28 05:49:21 +00003884 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003886 if (SS.isEmpty()) {
3887 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003888 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003889 }
Mike Stump1eb44332009-09-09 15:08:12 +00003890
John McCall9f54ad42009-12-10 09:41:52 +00003891 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003892 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003893 ForRedeclaration);
3894 Previous.setHideTags(false);
3895 if (S) {
3896 LookupName(Previous, S);
3897
3898 // It is really dumb that we have to do this.
3899 LookupResult::Filter F = Previous.makeFilter();
3900 while (F.hasNext()) {
3901 NamedDecl *D = F.next();
3902 if (!isDeclInScope(D, CurContext, S))
3903 F.erase();
3904 }
3905 F.done();
3906 } else {
3907 assert(IsInstantiation && "no scope in non-instantiation");
3908 assert(CurContext->isRecord() && "scope not record in instantiation");
3909 LookupQualifiedName(Previous, CurContext);
3910 }
3911
Mike Stump1eb44332009-09-09 15:08:12 +00003912 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003913 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3914
John McCall9f54ad42009-12-10 09:41:52 +00003915 // Check for invalid redeclarations.
3916 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3917 return 0;
3918
3919 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003920 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3921 return 0;
3922
John McCallaf8e6ed2009-11-12 03:15:40 +00003923 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003924 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003925 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003926 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003927 // FIXME: not all declaration name kinds are legal here
3928 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3929 UsingLoc, TypenameLoc,
3930 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003931 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003932 } else {
3933 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003934 UsingLoc, SS.getRange(),
3935 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003936 }
John McCalled976492009-12-04 22:46:56 +00003937 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003938 D = UsingDecl::Create(Context, CurContext,
3939 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003940 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003941 }
John McCalled976492009-12-04 22:46:56 +00003942 D->setAccess(AS);
3943 CurContext->addDecl(D);
3944
3945 if (!LookupContext) return D;
3946 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003947
John McCall77bb1aa2010-05-01 00:40:08 +00003948 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003949 UD->setInvalidDecl();
3950 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003951 }
3952
John McCall604e7f12009-12-08 07:46:18 +00003953 // Look up the target name.
3954
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003955 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003956
John McCall604e7f12009-12-08 07:46:18 +00003957 // Unlike most lookups, we don't always want to hide tag
3958 // declarations: tag names are visible through the using declaration
3959 // even if hidden by ordinary names, *except* in a dependent context
3960 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003961 if (!IsInstantiation)
3962 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003963
John McCalla24dc2e2009-11-17 02:14:36 +00003964 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003965
John McCallf36e02d2009-10-09 21:13:30 +00003966 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003967 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003968 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003969 UD->setInvalidDecl();
3970 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003971 }
3972
John McCalled976492009-12-04 22:46:56 +00003973 if (R.isAmbiguous()) {
3974 UD->setInvalidDecl();
3975 return UD;
3976 }
Mike Stump1eb44332009-09-09 15:08:12 +00003977
John McCall7ba107a2009-11-18 02:36:19 +00003978 if (IsTypeName) {
3979 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003980 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003981 Diag(IdentLoc, diag::err_using_typename_non_type);
3982 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3983 Diag((*I)->getUnderlyingDecl()->getLocation(),
3984 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003985 UD->setInvalidDecl();
3986 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003987 }
3988 } else {
3989 // If we asked for a non-typename and we got a type, error out,
3990 // but only if this is an instantiation of an unresolved using
3991 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003992 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003993 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3994 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003995 UD->setInvalidDecl();
3996 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003997 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003998 }
3999
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004000 // C++0x N2914 [namespace.udecl]p6:
4001 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004002 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004003 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4004 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004005 UD->setInvalidDecl();
4006 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004007 }
Mike Stump1eb44332009-09-09 15:08:12 +00004008
John McCall9f54ad42009-12-10 09:41:52 +00004009 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4010 if (!CheckUsingShadowDecl(UD, *I, Previous))
4011 BuildUsingShadowDecl(S, UD, *I);
4012 }
John McCall9488ea12009-11-17 05:59:44 +00004013
4014 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004015}
4016
John McCall9f54ad42009-12-10 09:41:52 +00004017/// Checks that the given using declaration is not an invalid
4018/// redeclaration. Note that this is checking only for the using decl
4019/// itself, not for any ill-formedness among the UsingShadowDecls.
4020bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4021 bool isTypeName,
4022 const CXXScopeSpec &SS,
4023 SourceLocation NameLoc,
4024 const LookupResult &Prev) {
4025 // C++03 [namespace.udecl]p8:
4026 // C++0x [namespace.udecl]p10:
4027 // A using-declaration is a declaration and can therefore be used
4028 // repeatedly where (and only where) multiple declarations are
4029 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004030 //
John McCall8a726212010-11-29 18:01:58 +00004031 // That's in non-member contexts.
4032 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004033 return false;
4034
4035 NestedNameSpecifier *Qual
4036 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4037
4038 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4039 NamedDecl *D = *I;
4040
4041 bool DTypename;
4042 NestedNameSpecifier *DQual;
4043 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4044 DTypename = UD->isTypeName();
4045 DQual = UD->getTargetNestedNameDecl();
4046 } else if (UnresolvedUsingValueDecl *UD
4047 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4048 DTypename = false;
4049 DQual = UD->getTargetNestedNameSpecifier();
4050 } else if (UnresolvedUsingTypenameDecl *UD
4051 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4052 DTypename = true;
4053 DQual = UD->getTargetNestedNameSpecifier();
4054 } else continue;
4055
4056 // using decls differ if one says 'typename' and the other doesn't.
4057 // FIXME: non-dependent using decls?
4058 if (isTypeName != DTypename) continue;
4059
4060 // using decls differ if they name different scopes (but note that
4061 // template instantiation can cause this check to trigger when it
4062 // didn't before instantiation).
4063 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4064 Context.getCanonicalNestedNameSpecifier(DQual))
4065 continue;
4066
4067 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004068 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004069 return true;
4070 }
4071
4072 return false;
4073}
4074
John McCall604e7f12009-12-08 07:46:18 +00004075
John McCalled976492009-12-04 22:46:56 +00004076/// Checks that the given nested-name qualifier used in a using decl
4077/// in the current context is appropriately related to the current
4078/// scope. If an error is found, diagnoses it and returns true.
4079bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4080 const CXXScopeSpec &SS,
4081 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004082 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004083
John McCall604e7f12009-12-08 07:46:18 +00004084 if (!CurContext->isRecord()) {
4085 // C++03 [namespace.udecl]p3:
4086 // C++0x [namespace.udecl]p8:
4087 // A using-declaration for a class member shall be a member-declaration.
4088
4089 // If we weren't able to compute a valid scope, it must be a
4090 // dependent class scope.
4091 if (!NamedContext || NamedContext->isRecord()) {
4092 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4093 << SS.getRange();
4094 return true;
4095 }
4096
4097 // Otherwise, everything is known to be fine.
4098 return false;
4099 }
4100
4101 // The current scope is a record.
4102
4103 // If the named context is dependent, we can't decide much.
4104 if (!NamedContext) {
4105 // FIXME: in C++0x, we can diagnose if we can prove that the
4106 // nested-name-specifier does not refer to a base class, which is
4107 // still possible in some cases.
4108
4109 // Otherwise we have to conservatively report that things might be
4110 // okay.
4111 return false;
4112 }
4113
4114 if (!NamedContext->isRecord()) {
4115 // Ideally this would point at the last name in the specifier,
4116 // but we don't have that level of source info.
4117 Diag(SS.getRange().getBegin(),
4118 diag::err_using_decl_nested_name_specifier_is_not_class)
4119 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4120 return true;
4121 }
4122
Douglas Gregor6fb07292010-12-21 07:41:49 +00004123 if (!NamedContext->isDependentContext() &&
4124 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4125 return true;
4126
John McCall604e7f12009-12-08 07:46:18 +00004127 if (getLangOptions().CPlusPlus0x) {
4128 // C++0x [namespace.udecl]p3:
4129 // In a using-declaration used as a member-declaration, the
4130 // nested-name-specifier shall name a base class of the class
4131 // being defined.
4132
4133 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4134 cast<CXXRecordDecl>(NamedContext))) {
4135 if (CurContext == NamedContext) {
4136 Diag(NameLoc,
4137 diag::err_using_decl_nested_name_specifier_is_current_class)
4138 << SS.getRange();
4139 return true;
4140 }
4141
4142 Diag(SS.getRange().getBegin(),
4143 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4144 << (NestedNameSpecifier*) SS.getScopeRep()
4145 << cast<CXXRecordDecl>(CurContext)
4146 << SS.getRange();
4147 return true;
4148 }
4149
4150 return false;
4151 }
4152
4153 // C++03 [namespace.udecl]p4:
4154 // A using-declaration used as a member-declaration shall refer
4155 // to a member of a base class of the class being defined [etc.].
4156
4157 // Salient point: SS doesn't have to name a base class as long as
4158 // lookup only finds members from base classes. Therefore we can
4159 // diagnose here only if we can prove that that can't happen,
4160 // i.e. if the class hierarchies provably don't intersect.
4161
4162 // TODO: it would be nice if "definitely valid" results were cached
4163 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4164 // need to be repeated.
4165
4166 struct UserData {
4167 llvm::DenseSet<const CXXRecordDecl*> Bases;
4168
4169 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4170 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4171 Data->Bases.insert(Base);
4172 return true;
4173 }
4174
4175 bool hasDependentBases(const CXXRecordDecl *Class) {
4176 return !Class->forallBases(collect, this);
4177 }
4178
4179 /// Returns true if the base is dependent or is one of the
4180 /// accumulated base classes.
4181 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4182 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4183 return !Data->Bases.count(Base);
4184 }
4185
4186 bool mightShareBases(const CXXRecordDecl *Class) {
4187 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4188 }
4189 };
4190
4191 UserData Data;
4192
4193 // Returns false if we find a dependent base.
4194 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4195 return false;
4196
4197 // Returns false if the class has a dependent base or if it or one
4198 // of its bases is present in the base set of the current context.
4199 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4200 return false;
4201
4202 Diag(SS.getRange().getBegin(),
4203 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4204 << (NestedNameSpecifier*) SS.getScopeRep()
4205 << cast<CXXRecordDecl>(CurContext)
4206 << SS.getRange();
4207
4208 return true;
John McCalled976492009-12-04 22:46:56 +00004209}
4210
John McCalld226f652010-08-21 09:40:31 +00004211Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004212 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004213 SourceLocation AliasLoc,
4214 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004215 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004216 SourceLocation IdentLoc,
4217 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Anders Carlsson81c85c42009-03-28 23:53:49 +00004219 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004220 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4221 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004222
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004223 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004224 NamedDecl *PrevDecl
4225 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4226 ForRedeclaration);
4227 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4228 PrevDecl = 0;
4229
4230 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004231 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004232 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004233 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004234 // FIXME: At some point, we'll want to create the (redundant)
4235 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004236 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004237 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004238 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004239 }
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004241 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4242 diag::err_redefinition_different_kind;
4243 Diag(AliasLoc, DiagID) << Alias;
4244 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004245 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004246 }
4247
John McCalla24dc2e2009-11-17 02:14:36 +00004248 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004249 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004250
John McCallf36e02d2009-10-09 21:13:30 +00004251 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004252 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4253 CTC_NoKeywords, 0)) {
4254 if (R.getAsSingle<NamespaceDecl>() ||
4255 R.getAsSingle<NamespaceAliasDecl>()) {
4256 if (DeclContext *DC = computeDeclContext(SS, false))
4257 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4258 << Ident << DC << Corrected << SS.getRange()
4259 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4260 else
4261 Diag(IdentLoc, diag::err_using_directive_suggest)
4262 << Ident << Corrected
4263 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4264
4265 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4266 << Corrected;
4267
4268 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004269 } else {
4270 R.clear();
4271 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004272 }
4273 }
4274
4275 if (R.empty()) {
4276 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004277 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004278 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004279 }
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004281 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004282 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4283 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004284 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004285 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004286
John McCall3dbd3d52010-02-16 06:53:13 +00004287 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004288 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004289}
4290
Douglas Gregor39957dc2010-05-01 15:04:51 +00004291namespace {
4292 /// \brief Scoped object used to handle the state changes required in Sema
4293 /// to implicitly define the body of a C++ member function;
4294 class ImplicitlyDefinedFunctionScope {
4295 Sema &S;
4296 DeclContext *PreviousContext;
4297
4298 public:
4299 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4300 : S(S), PreviousContext(S.CurContext)
4301 {
4302 S.CurContext = Method;
4303 S.PushFunctionScope();
4304 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4305 }
4306
4307 ~ImplicitlyDefinedFunctionScope() {
4308 S.PopExpressionEvaluationContext();
4309 S.PopFunctionOrBlockScope();
4310 S.CurContext = PreviousContext;
4311 }
4312 };
4313}
4314
Sebastian Redl751025d2010-09-13 22:02:47 +00004315static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4316 CXXRecordDecl *D) {
4317 ASTContext &Context = Self.Context;
4318 QualType ClassType = Context.getTypeDeclType(D);
4319 DeclarationName ConstructorName
4320 = Context.DeclarationNames.getCXXConstructorName(
4321 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4322
4323 DeclContext::lookup_const_iterator Con, ConEnd;
4324 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4325 Con != ConEnd; ++Con) {
4326 // FIXME: In C++0x, a constructor template can be a default constructor.
4327 if (isa<FunctionTemplateDecl>(*Con))
4328 continue;
4329
4330 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4331 if (Constructor->isDefaultConstructor())
4332 return Constructor;
4333 }
4334 return 0;
4335}
4336
Douglas Gregor23c94db2010-07-02 17:43:08 +00004337CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4338 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004339 // C++ [class.ctor]p5:
4340 // A default constructor for a class X is a constructor of class X
4341 // that can be called without an argument. If there is no
4342 // user-declared constructor for class X, a default constructor is
4343 // implicitly declared. An implicitly-declared default constructor
4344 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004345 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4346 "Should not build implicit default constructor!");
4347
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004348 // C++ [except.spec]p14:
4349 // An implicitly declared special member function (Clause 12) shall have an
4350 // exception-specification. [...]
4351 ImplicitExceptionSpecification ExceptSpec(Context);
4352
4353 // Direct base-class destructors.
4354 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4355 BEnd = ClassDecl->bases_end();
4356 B != BEnd; ++B) {
4357 if (B->isVirtual()) // Handled below.
4358 continue;
4359
Douglas Gregor18274032010-07-03 00:47:00 +00004360 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4362 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4363 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004364 else if (CXXConstructorDecl *Constructor
4365 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004366 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004367 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004368 }
4369
4370 // Virtual base-class destructors.
4371 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4372 BEnd = ClassDecl->vbases_end();
4373 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004374 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4375 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4376 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4377 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4378 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004379 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004380 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004381 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004382 }
4383
4384 // Field destructors.
4385 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4386 FEnd = ClassDecl->field_end();
4387 F != FEnd; ++F) {
4388 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004389 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4390 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4391 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4392 ExceptSpec.CalledDecl(
4393 DeclareImplicitDefaultConstructor(FieldClassDecl));
4394 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004395 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004396 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004397 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004398 }
John McCalle23cf432010-12-14 08:05:40 +00004399
4400 FunctionProtoType::ExtProtoInfo EPI;
4401 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4402 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4403 EPI.NumExceptions = ExceptSpec.size();
4404 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004405
4406 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004407 CanQualType ClassType
4408 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4409 DeclarationName Name
4410 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004411 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004412 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004413 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004414 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004415 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004416 /*TInfo=*/0,
4417 /*isExplicit=*/false,
4418 /*isInline=*/true,
4419 /*isImplicitlyDeclared=*/true);
4420 DefaultCon->setAccess(AS_public);
4421 DefaultCon->setImplicit();
4422 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004423
4424 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004425 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4426
Douglas Gregor23c94db2010-07-02 17:43:08 +00004427 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004428 PushOnScopeChains(DefaultCon, S, false);
4429 ClassDecl->addDecl(DefaultCon);
4430
Douglas Gregor32df23e2010-07-01 22:02:46 +00004431 return DefaultCon;
4432}
4433
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004434void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4435 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004436 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004437 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004438 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004440 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004441 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004442
Douglas Gregor39957dc2010-05-01 15:04:51 +00004443 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004444 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004445 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004446 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004447 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004448 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004449 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004450 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004451 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004452
4453 SourceLocation Loc = Constructor->getLocation();
4454 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4455
4456 Constructor->setUsed();
4457 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004458}
4459
Douglas Gregor23c94db2010-07-02 17:43:08 +00004460CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004461 // C++ [class.dtor]p2:
4462 // If a class has no user-declared destructor, a destructor is
4463 // declared implicitly. An implicitly-declared destructor is an
4464 // inline public member of its class.
4465
4466 // C++ [except.spec]p14:
4467 // An implicitly declared special member function (Clause 12) shall have
4468 // an exception-specification.
4469 ImplicitExceptionSpecification ExceptSpec(Context);
4470
4471 // Direct base-class destructors.
4472 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4473 BEnd = ClassDecl->bases_end();
4474 B != BEnd; ++B) {
4475 if (B->isVirtual()) // Handled below.
4476 continue;
4477
4478 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4479 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004480 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004481 }
4482
4483 // Virtual base-class destructors.
4484 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4485 BEnd = ClassDecl->vbases_end();
4486 B != BEnd; ++B) {
4487 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4488 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004489 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004490 }
4491
4492 // Field destructors.
4493 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4494 FEnd = ClassDecl->field_end();
4495 F != FEnd; ++F) {
4496 if (const RecordType *RecordTy
4497 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4498 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004499 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004500 }
4501
Douglas Gregor4923aa22010-07-02 20:37:36 +00004502 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004503 FunctionProtoType::ExtProtoInfo EPI;
4504 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4505 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4506 EPI.NumExceptions = ExceptSpec.size();
4507 EPI.Exceptions = ExceptSpec.data();
4508 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004509
4510 CanQualType ClassType
4511 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4512 DeclarationName Name
4513 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004514 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004515 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004516 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004517 /*isInline=*/true,
4518 /*isImplicitlyDeclared=*/true);
4519 Destructor->setAccess(AS_public);
4520 Destructor->setImplicit();
4521 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004522
4523 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004524 ++ASTContext::NumImplicitDestructorsDeclared;
4525
4526 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004527 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004528 PushOnScopeChains(Destructor, S, false);
4529 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004530
4531 // This could be uniqued if it ever proves significant.
4532 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4533
4534 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004535
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004536 return Destructor;
4537}
4538
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004539void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004540 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004541 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004542 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004543 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004544 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004545
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004546 if (Destructor->isInvalidDecl())
4547 return;
4548
Douglas Gregor39957dc2010-05-01 15:04:51 +00004549 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004550
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004551 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004552 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4553 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004554
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004555 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004556 Diag(CurrentLocation, diag::note_member_synthesized_at)
4557 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4558
4559 Destructor->setInvalidDecl();
4560 return;
4561 }
4562
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004563 SourceLocation Loc = Destructor->getLocation();
4564 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4565
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004566 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004567 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004568}
4569
Douglas Gregor06a9f362010-05-01 20:49:11 +00004570/// \brief Builds a statement that copies the given entity from \p From to
4571/// \c To.
4572///
4573/// This routine is used to copy the members of a class with an
4574/// implicitly-declared copy assignment operator. When the entities being
4575/// copied are arrays, this routine builds for loops to copy them.
4576///
4577/// \param S The Sema object used for type-checking.
4578///
4579/// \param Loc The location where the implicit copy is being generated.
4580///
4581/// \param T The type of the expressions being copied. Both expressions must
4582/// have this type.
4583///
4584/// \param To The expression we are copying to.
4585///
4586/// \param From The expression we are copying from.
4587///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004588/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4589/// Otherwise, it's a non-static member subobject.
4590///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004591/// \param Depth Internal parameter recording the depth of the recursion.
4592///
4593/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004594static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004595BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004596 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004597 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004598 // C++0x [class.copy]p30:
4599 // Each subobject is assigned in the manner appropriate to its type:
4600 //
4601 // - if the subobject is of class type, the copy assignment operator
4602 // for the class is used (as if by explicit qualification; that is,
4603 // ignoring any possible virtual overriding functions in more derived
4604 // classes);
4605 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4606 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4607
4608 // Look for operator=.
4609 DeclarationName Name
4610 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4611 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4612 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4613
4614 // Filter out any result that isn't a copy-assignment operator.
4615 LookupResult::Filter F = OpLookup.makeFilter();
4616 while (F.hasNext()) {
4617 NamedDecl *D = F.next();
4618 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4619 if (Method->isCopyAssignmentOperator())
4620 continue;
4621
4622 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004623 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004624 F.done();
4625
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004626 // Suppress the protected check (C++ [class.protected]) for each of the
4627 // assignment operators we found. This strange dance is required when
4628 // we're assigning via a base classes's copy-assignment operator. To
4629 // ensure that we're getting the right base class subobject (without
4630 // ambiguities), we need to cast "this" to that subobject type; to
4631 // ensure that we don't go through the virtual call mechanism, we need
4632 // to qualify the operator= name with the base class (see below). However,
4633 // this means that if the base class has a protected copy assignment
4634 // operator, the protected member access check will fail. So, we
4635 // rewrite "protected" access to "public" access in this case, since we
4636 // know by construction that we're calling from a derived class.
4637 if (CopyingBaseSubobject) {
4638 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4639 L != LEnd; ++L) {
4640 if (L.getAccess() == AS_protected)
4641 L.setAccess(AS_public);
4642 }
4643 }
4644
Douglas Gregor06a9f362010-05-01 20:49:11 +00004645 // Create the nested-name-specifier that will be used to qualify the
4646 // reference to operator=; this is required to suppress the virtual
4647 // call mechanism.
4648 CXXScopeSpec SS;
4649 SS.setRange(Loc);
4650 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4651 T.getTypePtr()));
4652
4653 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004654 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004655 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004656 /*FirstQualifierInScope=*/0, OpLookup,
4657 /*TemplateArgs=*/0,
4658 /*SuppressQualifierCheck=*/true);
4659 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004660 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004661
4662 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004663
John McCall60d7b3a2010-08-24 06:29:42 +00004664 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004665 OpEqualRef.takeAs<Expr>(),
4666 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004667 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004668 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004669
4670 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004671 }
John McCallb0207482010-03-16 06:11:48 +00004672
Douglas Gregor06a9f362010-05-01 20:49:11 +00004673 // - if the subobject is of scalar type, the built-in assignment
4674 // operator is used.
4675 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4676 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004678 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004679 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004680
4681 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004682 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004683
4684 // - if the subobject is an array, each element is assigned, in the
4685 // manner appropriate to the element type;
4686
4687 // Construct a loop over the array bounds, e.g.,
4688 //
4689 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4690 //
4691 // that will copy each of the array elements.
4692 QualType SizeType = S.Context.getSizeType();
4693
4694 // Create the iteration variable.
4695 IdentifierInfo *IterationVarName = 0;
4696 {
4697 llvm::SmallString<8> Str;
4698 llvm::raw_svector_ostream OS(Str);
4699 OS << "__i" << Depth;
4700 IterationVarName = &S.Context.Idents.get(OS.str());
4701 }
4702 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4703 IterationVarName, SizeType,
4704 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004705 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004706
4707 // Initialize the iteration variable to zero.
4708 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004709 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004710
4711 // Create a reference to the iteration variable; we'll use this several
4712 // times throughout.
4713 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00004714 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004715 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4716
4717 // Create the DeclStmt that holds the iteration variable.
4718 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4719
4720 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004721 llvm::APInt Upper
4722 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004723 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00004724 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00004725 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4726 BO_NE, S.Context.BoolTy,
4727 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004728
4729 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004730 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00004731 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4732 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004733
4734 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004735 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4736 IterationVarRef, Loc));
4737 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4738 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004739
4740 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00004741 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4742 To, From, CopyingBaseSubobject,
4743 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004744 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004745 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004746
4747 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004748 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004749 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004750 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004751 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004752}
4753
Douglas Gregora376d102010-07-02 21:50:04 +00004754/// \brief Determine whether the given class has a copy assignment operator
4755/// that accepts a const-qualified argument.
4756static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4757 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4758
4759 if (!Class->hasDeclaredCopyAssignment())
4760 S.DeclareImplicitCopyAssignment(Class);
4761
4762 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4763 DeclarationName OpName
4764 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4765
4766 DeclContext::lookup_const_iterator Op, OpEnd;
4767 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4768 // C++ [class.copy]p9:
4769 // A user-declared copy assignment operator is a non-static non-template
4770 // member function of class X with exactly one parameter of type X, X&,
4771 // const X&, volatile X& or const volatile X&.
4772 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4773 if (!Method)
4774 continue;
4775
4776 if (Method->isStatic())
4777 continue;
4778 if (Method->getPrimaryTemplate())
4779 continue;
4780 const FunctionProtoType *FnType =
4781 Method->getType()->getAs<FunctionProtoType>();
4782 assert(FnType && "Overloaded operator has no prototype.");
4783 // Don't assert on this; an invalid decl might have been left in the AST.
4784 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4785 continue;
4786 bool AcceptsConst = true;
4787 QualType ArgType = FnType->getArgType(0);
4788 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4789 ArgType = Ref->getPointeeType();
4790 // Is it a non-const lvalue reference?
4791 if (!ArgType.isConstQualified())
4792 AcceptsConst = false;
4793 }
4794 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4795 continue;
4796
4797 // We have a single argument of type cv X or cv X&, i.e. we've found the
4798 // copy assignment operator. Return whether it accepts const arguments.
4799 return AcceptsConst;
4800 }
4801 assert(Class->isInvalidDecl() &&
4802 "No copy assignment operator declared in valid code.");
4803 return false;
4804}
4805
Douglas Gregor23c94db2010-07-02 17:43:08 +00004806CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004807 // Note: The following rules are largely analoguous to the copy
4808 // constructor rules. Note that virtual bases are not taken into account
4809 // for determining the argument type of the operator. Note also that
4810 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004811
4812
Douglas Gregord3c35902010-07-01 16:36:15 +00004813 // C++ [class.copy]p10:
4814 // If the class definition does not explicitly declare a copy
4815 // assignment operator, one is declared implicitly.
4816 // The implicitly-defined copy assignment operator for a class X
4817 // will have the form
4818 //
4819 // X& X::operator=(const X&)
4820 //
4821 // if
4822 bool HasConstCopyAssignment = true;
4823
4824 // -- each direct base class B of X has a copy assignment operator
4825 // whose parameter is of type const B&, const volatile B& or B,
4826 // and
4827 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4828 BaseEnd = ClassDecl->bases_end();
4829 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4830 assert(!Base->getType()->isDependentType() &&
4831 "Cannot generate implicit members for class with dependent bases.");
4832 const CXXRecordDecl *BaseClassDecl
4833 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004834 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004835 }
4836
4837 // -- for all the nonstatic data members of X that are of a class
4838 // type M (or array thereof), each such class type has a copy
4839 // assignment operator whose parameter is of type const M&,
4840 // const volatile M& or M.
4841 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4842 FieldEnd = ClassDecl->field_end();
4843 HasConstCopyAssignment && Field != FieldEnd;
4844 ++Field) {
4845 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4846 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4847 const CXXRecordDecl *FieldClassDecl
4848 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004849 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004850 }
4851 }
4852
4853 // Otherwise, the implicitly declared copy assignment operator will
4854 // have the form
4855 //
4856 // X& X::operator=(X&)
4857 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4858 QualType RetType = Context.getLValueReferenceType(ArgType);
4859 if (HasConstCopyAssignment)
4860 ArgType = ArgType.withConst();
4861 ArgType = Context.getLValueReferenceType(ArgType);
4862
Douglas Gregorb87786f2010-07-01 17:48:08 +00004863 // C++ [except.spec]p14:
4864 // An implicitly declared special member function (Clause 12) shall have an
4865 // exception-specification. [...]
4866 ImplicitExceptionSpecification ExceptSpec(Context);
4867 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4868 BaseEnd = ClassDecl->bases_end();
4869 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004870 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004871 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004872
4873 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4874 DeclareImplicitCopyAssignment(BaseClassDecl);
4875
Douglas Gregorb87786f2010-07-01 17:48:08 +00004876 if (CXXMethodDecl *CopyAssign
4877 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4878 ExceptSpec.CalledDecl(CopyAssign);
4879 }
4880 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4881 FieldEnd = ClassDecl->field_end();
4882 Field != FieldEnd;
4883 ++Field) {
4884 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4885 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004886 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004887 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004888
4889 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4890 DeclareImplicitCopyAssignment(FieldClassDecl);
4891
Douglas Gregorb87786f2010-07-01 17:48:08 +00004892 if (CXXMethodDecl *CopyAssign
4893 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4894 ExceptSpec.CalledDecl(CopyAssign);
4895 }
4896 }
4897
Douglas Gregord3c35902010-07-01 16:36:15 +00004898 // An implicitly-declared copy assignment operator is an inline public
4899 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00004900 FunctionProtoType::ExtProtoInfo EPI;
4901 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4902 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4903 EPI.NumExceptions = ExceptSpec.size();
4904 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00004905 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004906 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004907 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004908 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00004909 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00004910 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004911 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004912 /*isInline=*/true);
4913 CopyAssignment->setAccess(AS_public);
4914 CopyAssignment->setImplicit();
4915 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004916
4917 // Add the parameter to the operator.
4918 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4919 ClassDecl->getLocation(),
4920 /*Id=*/0,
4921 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004922 SC_None,
4923 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004924 CopyAssignment->setParams(&FromParam, 1);
4925
Douglas Gregora376d102010-07-02 21:50:04 +00004926 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004927 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4928
Douglas Gregor23c94db2010-07-02 17:43:08 +00004929 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004930 PushOnScopeChains(CopyAssignment, S, false);
4931 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004932
4933 AddOverriddenMethods(ClassDecl, CopyAssignment);
4934 return CopyAssignment;
4935}
4936
Douglas Gregor06a9f362010-05-01 20:49:11 +00004937void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4938 CXXMethodDecl *CopyAssignOperator) {
4939 assert((CopyAssignOperator->isImplicit() &&
4940 CopyAssignOperator->isOverloadedOperator() &&
4941 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004942 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004943 "DefineImplicitCopyAssignment called for wrong function");
4944
4945 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4946
4947 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4948 CopyAssignOperator->setInvalidDecl();
4949 return;
4950 }
4951
4952 CopyAssignOperator->setUsed();
4953
4954 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004955 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004956
4957 // C++0x [class.copy]p30:
4958 // The implicitly-defined or explicitly-defaulted copy assignment operator
4959 // for a non-union class X performs memberwise copy assignment of its
4960 // subobjects. The direct base classes of X are assigned first, in the
4961 // order of their declaration in the base-specifier-list, and then the
4962 // immediate non-static data members of X are assigned, in the order in
4963 // which they were declared in the class definition.
4964
4965 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004966 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004967
4968 // The parameter for the "other" object, which we are copying from.
4969 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4970 Qualifiers OtherQuals = Other->getType().getQualifiers();
4971 QualType OtherRefType = Other->getType();
4972 if (const LValueReferenceType *OtherRef
4973 = OtherRefType->getAs<LValueReferenceType>()) {
4974 OtherRefType = OtherRef->getPointeeType();
4975 OtherQuals = OtherRefType.getQualifiers();
4976 }
4977
4978 // Our location for everything implicitly-generated.
4979 SourceLocation Loc = CopyAssignOperator->getLocation();
4980
4981 // Construct a reference to the "other" object. We'll be using this
4982 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00004983 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004984 assert(OtherRef && "Reference to parameter cannot fail!");
4985
4986 // Construct the "this" pointer. We'll be using this throughout the generated
4987 // ASTs.
4988 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4989 assert(This && "Reference to this cannot fail!");
4990
4991 // Assign base classes.
4992 bool Invalid = false;
4993 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4994 E = ClassDecl->bases_end(); Base != E; ++Base) {
4995 // Form the assignment:
4996 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4997 QualType BaseType = Base->getType().getUnqualifiedType();
4998 CXXRecordDecl *BaseClassDecl = 0;
4999 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
5000 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
5001 else {
5002 Invalid = true;
5003 continue;
5004 }
5005
John McCallf871d0c2010-08-07 06:22:56 +00005006 CXXCastPath BasePath;
5007 BasePath.push_back(Base);
5008
Douglas Gregor06a9f362010-05-01 20:49:11 +00005009 // Construct the "from" expression, which is an implicit cast to the
5010 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005011 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005012 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005013 CK_UncheckedDerivedToBase,
5014 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005015
5016 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005017 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005018
5019 // Implicitly cast "this" to the appropriately-qualified base type.
5020 Expr *ToE = To.takeAs<Expr>();
5021 ImpCastExprToType(ToE,
5022 Context.getCVRQualifiedType(BaseType,
5023 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005024 CK_UncheckedDerivedToBase,
5025 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005026 To = Owned(ToE);
5027
5028 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005029 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005030 To.get(), From,
5031 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005032 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005033 Diag(CurrentLocation, diag::note_member_synthesized_at)
5034 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5035 CopyAssignOperator->setInvalidDecl();
5036 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005037 }
5038
5039 // Success! Record the copy.
5040 Statements.push_back(Copy.takeAs<Expr>());
5041 }
5042
5043 // \brief Reference to the __builtin_memcpy function.
5044 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005045 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005046 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005047
5048 // Assign non-static members.
5049 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5050 FieldEnd = ClassDecl->field_end();
5051 Field != FieldEnd; ++Field) {
5052 // Check for members of reference type; we can't copy those.
5053 if (Field->getType()->isReferenceType()) {
5054 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5055 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5056 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005057 Diag(CurrentLocation, diag::note_member_synthesized_at)
5058 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005059 Invalid = true;
5060 continue;
5061 }
5062
5063 // Check for members of const-qualified, non-class type.
5064 QualType BaseType = Context.getBaseElementType(Field->getType());
5065 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5066 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5067 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5068 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005069 Diag(CurrentLocation, diag::note_member_synthesized_at)
5070 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005071 Invalid = true;
5072 continue;
5073 }
5074
5075 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005076 if (FieldType->isIncompleteArrayType()) {
5077 assert(ClassDecl->hasFlexibleArrayMember() &&
5078 "Incomplete array type is not valid");
5079 continue;
5080 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005081
5082 // Build references to the field in the object we're copying from and to.
5083 CXXScopeSpec SS; // Intentionally empty
5084 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5085 LookupMemberName);
5086 MemberLookup.addDecl(*Field);
5087 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005088 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005089 Loc, /*IsArrow=*/false,
5090 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005091 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005092 Loc, /*IsArrow=*/true,
5093 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005094 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5095 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5096
5097 // If the field should be copied with __builtin_memcpy rather than via
5098 // explicit assignments, do so. This optimization only applies for arrays
5099 // of scalars and arrays of class type with trivial copy-assignment
5100 // operators.
5101 if (FieldType->isArrayType() &&
5102 (!BaseType->isRecordType() ||
5103 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5104 ->hasTrivialCopyAssignment())) {
5105 // Compute the size of the memory buffer to be copied.
5106 QualType SizeType = Context.getSizeType();
5107 llvm::APInt Size(Context.getTypeSize(SizeType),
5108 Context.getTypeSizeInChars(BaseType).getQuantity());
5109 for (const ConstantArrayType *Array
5110 = Context.getAsConstantArrayType(FieldType);
5111 Array;
5112 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005113 llvm::APInt ArraySize
5114 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005115 Size *= ArraySize;
5116 }
5117
5118 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005119 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5120 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005121
5122 bool NeedsCollectableMemCpy =
5123 (BaseType->isRecordType() &&
5124 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5125
5126 if (NeedsCollectableMemCpy) {
5127 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005128 // Create a reference to the __builtin_objc_memmove_collectable function.
5129 LookupResult R(*this,
5130 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005131 Loc, LookupOrdinaryName);
5132 LookupName(R, TUScope, true);
5133
5134 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5135 if (!CollectableMemCpy) {
5136 // Something went horribly wrong earlier, and we will have
5137 // complained about it.
5138 Invalid = true;
5139 continue;
5140 }
5141
5142 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5143 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005144 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005145 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5146 }
5147 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005148 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005149 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005150 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5151 LookupOrdinaryName);
5152 LookupName(R, TUScope, true);
5153
5154 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5155 if (!BuiltinMemCpy) {
5156 // Something went horribly wrong earlier, and we will have complained
5157 // about it.
5158 Invalid = true;
5159 continue;
5160 }
5161
5162 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5163 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005164 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005165 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5166 }
5167
John McCallca0408f2010-08-23 06:44:23 +00005168 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005169 CallArgs.push_back(To.takeAs<Expr>());
5170 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005171 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005172 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005173 if (NeedsCollectableMemCpy)
5174 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005175 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005176 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005177 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005178 else
5179 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005180 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005181 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005182 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005183
Douglas Gregor06a9f362010-05-01 20:49:11 +00005184 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5185 Statements.push_back(Call.takeAs<Expr>());
5186 continue;
5187 }
5188
5189 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005190 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005191 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005192 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005193 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005194 Diag(CurrentLocation, diag::note_member_synthesized_at)
5195 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5196 CopyAssignOperator->setInvalidDecl();
5197 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005198 }
5199
5200 // Success! Record the copy.
5201 Statements.push_back(Copy.takeAs<Stmt>());
5202 }
5203
5204 if (!Invalid) {
5205 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005206 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005207
John McCall60d7b3a2010-08-24 06:29:42 +00005208 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005209 if (Return.isInvalid())
5210 Invalid = true;
5211 else {
5212 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005213
5214 if (Trap.hasErrorOccurred()) {
5215 Diag(CurrentLocation, diag::note_member_synthesized_at)
5216 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5217 Invalid = true;
5218 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005219 }
5220 }
5221
5222 if (Invalid) {
5223 CopyAssignOperator->setInvalidDecl();
5224 return;
5225 }
5226
John McCall60d7b3a2010-08-24 06:29:42 +00005227 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005228 /*isStmtExpr=*/false);
5229 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5230 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005231}
5232
Douglas Gregor23c94db2010-07-02 17:43:08 +00005233CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5234 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005235 // C++ [class.copy]p4:
5236 // If the class definition does not explicitly declare a copy
5237 // constructor, one is declared implicitly.
5238
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005239 // C++ [class.copy]p5:
5240 // The implicitly-declared copy constructor for a class X will
5241 // have the form
5242 //
5243 // X::X(const X&)
5244 //
5245 // if
5246 bool HasConstCopyConstructor = true;
5247
5248 // -- each direct or virtual base class B of X has a copy
5249 // constructor whose first parameter is of type const B& or
5250 // const volatile B&, and
5251 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5252 BaseEnd = ClassDecl->bases_end();
5253 HasConstCopyConstructor && Base != BaseEnd;
5254 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005255 // Virtual bases are handled below.
5256 if (Base->isVirtual())
5257 continue;
5258
Douglas Gregor22584312010-07-02 23:41:54 +00005259 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005260 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005261 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5262 DeclareImplicitCopyConstructor(BaseClassDecl);
5263
Douglas Gregor598a8542010-07-01 18:27:03 +00005264 HasConstCopyConstructor
5265 = BaseClassDecl->hasConstCopyConstructor(Context);
5266 }
5267
5268 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5269 BaseEnd = ClassDecl->vbases_end();
5270 HasConstCopyConstructor && Base != BaseEnd;
5271 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005272 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005273 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005274 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5275 DeclareImplicitCopyConstructor(BaseClassDecl);
5276
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005277 HasConstCopyConstructor
5278 = BaseClassDecl->hasConstCopyConstructor(Context);
5279 }
5280
5281 // -- for all the nonstatic data members of X that are of a
5282 // class type M (or array thereof), each such class type
5283 // has a copy constructor whose first parameter is of type
5284 // const M& or const volatile M&.
5285 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5286 FieldEnd = ClassDecl->field_end();
5287 HasConstCopyConstructor && Field != FieldEnd;
5288 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005289 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005290 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005291 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005292 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005293 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5294 DeclareImplicitCopyConstructor(FieldClassDecl);
5295
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005296 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005297 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005298 }
5299 }
5300
5301 // Otherwise, the implicitly declared copy constructor will have
5302 // the form
5303 //
5304 // X::X(X&)
5305 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5306 QualType ArgType = ClassType;
5307 if (HasConstCopyConstructor)
5308 ArgType = ArgType.withConst();
5309 ArgType = Context.getLValueReferenceType(ArgType);
5310
Douglas Gregor0d405db2010-07-01 20:59:04 +00005311 // C++ [except.spec]p14:
5312 // An implicitly declared special member function (Clause 12) shall have an
5313 // exception-specification. [...]
5314 ImplicitExceptionSpecification ExceptSpec(Context);
5315 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5316 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5317 BaseEnd = ClassDecl->bases_end();
5318 Base != BaseEnd;
5319 ++Base) {
5320 // Virtual bases are handled below.
5321 if (Base->isVirtual())
5322 continue;
5323
Douglas Gregor22584312010-07-02 23:41:54 +00005324 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005325 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005326 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5327 DeclareImplicitCopyConstructor(BaseClassDecl);
5328
Douglas Gregor0d405db2010-07-01 20:59:04 +00005329 if (CXXConstructorDecl *CopyConstructor
5330 = BaseClassDecl->getCopyConstructor(Context, Quals))
5331 ExceptSpec.CalledDecl(CopyConstructor);
5332 }
5333 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5334 BaseEnd = ClassDecl->vbases_end();
5335 Base != BaseEnd;
5336 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005337 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005338 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005339 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5340 DeclareImplicitCopyConstructor(BaseClassDecl);
5341
Douglas Gregor0d405db2010-07-01 20:59:04 +00005342 if (CXXConstructorDecl *CopyConstructor
5343 = BaseClassDecl->getCopyConstructor(Context, Quals))
5344 ExceptSpec.CalledDecl(CopyConstructor);
5345 }
5346 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5347 FieldEnd = ClassDecl->field_end();
5348 Field != FieldEnd;
5349 ++Field) {
5350 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5351 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005352 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005353 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005354 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5355 DeclareImplicitCopyConstructor(FieldClassDecl);
5356
Douglas Gregor0d405db2010-07-01 20:59:04 +00005357 if (CXXConstructorDecl *CopyConstructor
5358 = FieldClassDecl->getCopyConstructor(Context, Quals))
5359 ExceptSpec.CalledDecl(CopyConstructor);
5360 }
5361 }
5362
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005363 // An implicitly-declared copy constructor is an inline public
5364 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005365 FunctionProtoType::ExtProtoInfo EPI;
5366 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5367 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5368 EPI.NumExceptions = ExceptSpec.size();
5369 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005370 DeclarationName Name
5371 = Context.DeclarationNames.getCXXConstructorName(
5372 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005373 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005374 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005375 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005376 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005377 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005378 /*TInfo=*/0,
5379 /*isExplicit=*/false,
5380 /*isInline=*/true,
5381 /*isImplicitlyDeclared=*/true);
5382 CopyConstructor->setAccess(AS_public);
5383 CopyConstructor->setImplicit();
5384 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5385
Douglas Gregor22584312010-07-02 23:41:54 +00005386 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005387 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5388
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005389 // Add the parameter to the constructor.
5390 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5391 ClassDecl->getLocation(),
5392 /*IdentifierInfo=*/0,
5393 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005394 SC_None,
5395 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005396 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005397 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005398 PushOnScopeChains(CopyConstructor, S, false);
5399 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005400
5401 return CopyConstructor;
5402}
5403
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005404void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5405 CXXConstructorDecl *CopyConstructor,
5406 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005407 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005408 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005409 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005410 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Anders Carlsson63010a72010-04-23 16:24:12 +00005412 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005413 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005414
Douglas Gregor39957dc2010-05-01 15:04:51 +00005415 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005416 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005417
Sean Huntcbb67482011-01-08 20:30:50 +00005418 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005419 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005420 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005421 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005422 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005423 } else {
5424 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5425 CopyConstructor->getLocation(),
5426 MultiStmtArg(*this, 0, 0),
5427 /*isStmtExpr=*/false)
5428 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005429 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005430
5431 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005432}
5433
John McCall60d7b3a2010-08-24 06:29:42 +00005434ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005435Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005436 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005437 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005438 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005439 unsigned ConstructKind,
5440 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005441 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005442
Douglas Gregor2f599792010-04-02 18:24:57 +00005443 // C++0x [class.copy]p34:
5444 // When certain criteria are met, an implementation is allowed to
5445 // omit the copy/move construction of a class object, even if the
5446 // copy/move constructor and/or destructor for the object have
5447 // side effects. [...]
5448 // - when a temporary class object that has not been bound to a
5449 // reference (12.2) would be copied/moved to a class object
5450 // with the same cv-unqualified type, the copy/move operation
5451 // can be omitted by constructing the temporary object
5452 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005453 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5454 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005455 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005456 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005457 }
Mike Stump1eb44332009-09-09 15:08:12 +00005458
5459 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005460 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005461 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005462}
5463
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005464/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5465/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005466ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005467Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5468 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005469 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005470 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005471 unsigned ConstructKind,
5472 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005473 unsigned NumExprs = ExprArgs.size();
5474 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005475
Douglas Gregor7edfb692009-11-23 12:27:39 +00005476 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005477 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005478 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005479 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005480 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5481 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005482}
5483
Mike Stump1eb44332009-09-09 15:08:12 +00005484bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005485 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005486 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005487 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005488 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005489 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005490 move(Exprs), false, CXXConstructExpr::CK_Complete,
5491 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005492 if (TempResult.isInvalid())
5493 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005495 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005496 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005497 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005498 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005499 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005500
Anders Carlssonfe2de492009-08-25 05:18:00 +00005501 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005502}
5503
John McCall68c6c9a2010-02-02 09:10:11 +00005504void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5505 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005506 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005507 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005508 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005509 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005510 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005511 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005512 << VD->getDeclName()
5513 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005514
John McCallae792222010-09-18 05:25:11 +00005515 // TODO: this should be re-enabled for static locals by !CXAAtExit
5516 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005517 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005518 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005519}
5520
Mike Stump1eb44332009-09-09 15:08:12 +00005521/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005522/// ActOnDeclarator, when a C++ direct initializer is present.
5523/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005524void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005525 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005526 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005527 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005528 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005529
5530 // If there is no declaration, there was an error parsing it. Just ignore
5531 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005532 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005533 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005534
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005535 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5536 if (!VDecl) {
5537 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5538 RealDecl->setInvalidDecl();
5539 return;
5540 }
5541
Douglas Gregor83ddad32009-08-26 21:14:46 +00005542 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005543 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005544 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5545 //
5546 // Clients that want to distinguish between the two forms, can check for
5547 // direct initializer using VarDecl::hasCXXDirectInitializer().
5548 // A major benefit is that clients that don't particularly care about which
5549 // exactly form was it (like the CodeGen) can handle both cases without
5550 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005551
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005552 // C++ 8.5p11:
5553 // The form of initialization (using parentheses or '=') is generally
5554 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005555 // class type.
5556
Douglas Gregor4dffad62010-02-11 22:55:30 +00005557 if (!VDecl->getType()->isDependentType() &&
5558 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005559 diag::err_typecheck_decl_incomplete_type)) {
5560 VDecl->setInvalidDecl();
5561 return;
5562 }
5563
Douglas Gregor90f93822009-12-22 22:17:25 +00005564 // The variable can not have an abstract class type.
5565 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5566 diag::err_abstract_type_in_decl,
5567 AbstractVariableType))
5568 VDecl->setInvalidDecl();
5569
Sebastian Redl31310a22010-02-01 20:16:42 +00005570 const VarDecl *Def;
5571 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005572 Diag(VDecl->getLocation(), diag::err_redefinition)
5573 << VDecl->getDeclName();
5574 Diag(Def->getLocation(), diag::note_previous_definition);
5575 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005576 return;
5577 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005578
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005579 // C++ [class.static.data]p4
5580 // If a static data member is of const integral or const
5581 // enumeration type, its declaration in the class definition can
5582 // specify a constant-initializer which shall be an integral
5583 // constant expression (5.19). In that case, the member can appear
5584 // in integral constant expressions. The member shall still be
5585 // defined in a namespace scope if it is used in the program and the
5586 // namespace scope definition shall not contain an initializer.
5587 //
5588 // We already performed a redefinition check above, but for static
5589 // data members we also need to check whether there was an in-class
5590 // declaration with an initializer.
5591 const VarDecl* PrevInit = 0;
5592 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5593 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5594 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5595 return;
5596 }
5597
Douglas Gregora31040f2010-12-16 01:31:22 +00005598 bool IsDependent = false;
5599 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5600 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5601 VDecl->setInvalidDecl();
5602 return;
5603 }
5604
5605 if (Exprs.get()[I]->isTypeDependent())
5606 IsDependent = true;
5607 }
5608
Douglas Gregor4dffad62010-02-11 22:55:30 +00005609 // If either the declaration has a dependent type or if any of the
5610 // expressions is type-dependent, we represent the initialization
5611 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00005612 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00005613 // Let clients know that initialization was done with a direct initializer.
5614 VDecl->setCXXDirectInitializer(true);
5615
5616 // Store the initialization expressions as a ParenListExpr.
5617 unsigned NumExprs = Exprs.size();
5618 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5619 (Expr **)Exprs.release(),
5620 NumExprs, RParenLoc));
5621 return;
5622 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005623
5624 // Capture the variable that is being initialized and the style of
5625 // initialization.
5626 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5627
5628 // FIXME: Poor source location information.
5629 InitializationKind Kind
5630 = InitializationKind::CreateDirect(VDecl->getLocation(),
5631 LParenLoc, RParenLoc);
5632
5633 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005634 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005635 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005636 if (Result.isInvalid()) {
5637 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005638 return;
5639 }
John McCallb4eb64d2010-10-08 02:01:28 +00005640
5641 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005642
Douglas Gregor53c374f2010-12-07 00:41:46 +00005643 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00005644 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005645 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005646
John McCall4204f072010-08-02 21:13:48 +00005647 if (!VDecl->isInvalidDecl() &&
5648 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005649 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005650 !VDecl->getInit()->isConstantInitializer(Context,
5651 VDecl->getType()->isReferenceType()))
5652 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5653 << VDecl->getInit()->getSourceRange();
5654
John McCall68c6c9a2010-02-02 09:10:11 +00005655 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5656 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005657}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005658
Douglas Gregor39da0b82009-09-09 23:08:42 +00005659/// \brief Given a constructor and the set of arguments provided for the
5660/// constructor, convert the arguments and add any required default arguments
5661/// to form a proper call to this constructor.
5662///
5663/// \returns true if an error occurred, false otherwise.
5664bool
5665Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5666 MultiExprArg ArgsPtr,
5667 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005668 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005669 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5670 unsigned NumArgs = ArgsPtr.size();
5671 Expr **Args = (Expr **)ArgsPtr.get();
5672
5673 const FunctionProtoType *Proto
5674 = Constructor->getType()->getAs<FunctionProtoType>();
5675 assert(Proto && "Constructor without a prototype?");
5676 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005677
5678 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005679 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005680 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005681 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005682 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005683
5684 VariadicCallType CallType =
5685 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5686 llvm::SmallVector<Expr *, 8> AllArgs;
5687 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5688 Proto, 0, Args, NumArgs, AllArgs,
5689 CallType);
5690 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5691 ConvertedArgs.push_back(AllArgs[i]);
5692 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005693}
5694
Anders Carlsson20d45d22009-12-12 00:32:00 +00005695static inline bool
5696CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5697 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005698 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005699 if (isa<NamespaceDecl>(DC)) {
5700 return SemaRef.Diag(FnDecl->getLocation(),
5701 diag::err_operator_new_delete_declared_in_namespace)
5702 << FnDecl->getDeclName();
5703 }
5704
5705 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005706 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005707 return SemaRef.Diag(FnDecl->getLocation(),
5708 diag::err_operator_new_delete_declared_static)
5709 << FnDecl->getDeclName();
5710 }
5711
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005712 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005713}
5714
Anders Carlsson156c78e2009-12-13 17:53:43 +00005715static inline bool
5716CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5717 CanQualType ExpectedResultType,
5718 CanQualType ExpectedFirstParamType,
5719 unsigned DependentParamTypeDiag,
5720 unsigned InvalidParamTypeDiag) {
5721 QualType ResultType =
5722 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5723
5724 // Check that the result type is not dependent.
5725 if (ResultType->isDependentType())
5726 return SemaRef.Diag(FnDecl->getLocation(),
5727 diag::err_operator_new_delete_dependent_result_type)
5728 << FnDecl->getDeclName() << ExpectedResultType;
5729
5730 // Check that the result type is what we expect.
5731 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5732 return SemaRef.Diag(FnDecl->getLocation(),
5733 diag::err_operator_new_delete_invalid_result_type)
5734 << FnDecl->getDeclName() << ExpectedResultType;
5735
5736 // A function template must have at least 2 parameters.
5737 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5738 return SemaRef.Diag(FnDecl->getLocation(),
5739 diag::err_operator_new_delete_template_too_few_parameters)
5740 << FnDecl->getDeclName();
5741
5742 // The function decl must have at least 1 parameter.
5743 if (FnDecl->getNumParams() == 0)
5744 return SemaRef.Diag(FnDecl->getLocation(),
5745 diag::err_operator_new_delete_too_few_parameters)
5746 << FnDecl->getDeclName();
5747
5748 // Check the the first parameter type is not dependent.
5749 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5750 if (FirstParamType->isDependentType())
5751 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5752 << FnDecl->getDeclName() << ExpectedFirstParamType;
5753
5754 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005755 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005756 ExpectedFirstParamType)
5757 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5758 << FnDecl->getDeclName() << ExpectedFirstParamType;
5759
5760 return false;
5761}
5762
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005763static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005764CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005765 // C++ [basic.stc.dynamic.allocation]p1:
5766 // A program is ill-formed if an allocation function is declared in a
5767 // namespace scope other than global scope or declared static in global
5768 // scope.
5769 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5770 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005771
5772 CanQualType SizeTy =
5773 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5774
5775 // C++ [basic.stc.dynamic.allocation]p1:
5776 // The return type shall be void*. The first parameter shall have type
5777 // std::size_t.
5778 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5779 SizeTy,
5780 diag::err_operator_new_dependent_param_type,
5781 diag::err_operator_new_param_type))
5782 return true;
5783
5784 // C++ [basic.stc.dynamic.allocation]p1:
5785 // The first parameter shall not have an associated default argument.
5786 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005787 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005788 diag::err_operator_new_default_arg)
5789 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5790
5791 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005792}
5793
5794static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005795CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5796 // C++ [basic.stc.dynamic.deallocation]p1:
5797 // A program is ill-formed if deallocation functions are declared in a
5798 // namespace scope other than global scope or declared static in global
5799 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005800 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5801 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005802
5803 // C++ [basic.stc.dynamic.deallocation]p2:
5804 // Each deallocation function shall return void and its first parameter
5805 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005806 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5807 SemaRef.Context.VoidPtrTy,
5808 diag::err_operator_delete_dependent_param_type,
5809 diag::err_operator_delete_param_type))
5810 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005811
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005812 return false;
5813}
5814
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005815/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5816/// of this overloaded operator is well-formed. If so, returns false;
5817/// otherwise, emits appropriate diagnostics and returns true.
5818bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005819 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005820 "Expected an overloaded operator declaration");
5821
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005822 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5823
Mike Stump1eb44332009-09-09 15:08:12 +00005824 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005825 // The allocation and deallocation functions, operator new,
5826 // operator new[], operator delete and operator delete[], are
5827 // described completely in 3.7.3. The attributes and restrictions
5828 // found in the rest of this subclause do not apply to them unless
5829 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005830 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005831 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005832
Anders Carlssona3ccda52009-12-12 00:26:23 +00005833 if (Op == OO_New || Op == OO_Array_New)
5834 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005835
5836 // C++ [over.oper]p6:
5837 // An operator function shall either be a non-static member
5838 // function or be a non-member function and have at least one
5839 // parameter whose type is a class, a reference to a class, an
5840 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005841 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5842 if (MethodDecl->isStatic())
5843 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005844 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005845 } else {
5846 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005847 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5848 ParamEnd = FnDecl->param_end();
5849 Param != ParamEnd; ++Param) {
5850 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005851 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5852 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005853 ClassOrEnumParam = true;
5854 break;
5855 }
5856 }
5857
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005858 if (!ClassOrEnumParam)
5859 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005860 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005861 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005862 }
5863
5864 // C++ [over.oper]p8:
5865 // An operator function cannot have default arguments (8.3.6),
5866 // except where explicitly stated below.
5867 //
Mike Stump1eb44332009-09-09 15:08:12 +00005868 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005869 // (C++ [over.call]p1).
5870 if (Op != OO_Call) {
5871 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5872 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005873 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005874 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005875 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005876 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005877 }
5878 }
5879
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005880 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5881 { false, false, false }
5882#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5883 , { Unary, Binary, MemberOnly }
5884#include "clang/Basic/OperatorKinds.def"
5885 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005886
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005887 bool CanBeUnaryOperator = OperatorUses[Op][0];
5888 bool CanBeBinaryOperator = OperatorUses[Op][1];
5889 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005890
5891 // C++ [over.oper]p8:
5892 // [...] Operator functions cannot have more or fewer parameters
5893 // than the number required for the corresponding operator, as
5894 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005895 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005896 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005897 if (Op != OO_Call &&
5898 ((NumParams == 1 && !CanBeUnaryOperator) ||
5899 (NumParams == 2 && !CanBeBinaryOperator) ||
5900 (NumParams < 1) || (NumParams > 2))) {
5901 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005902 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005903 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005904 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005905 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005906 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005907 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005908 assert(CanBeBinaryOperator &&
5909 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005910 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005911 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005912
Chris Lattner416e46f2008-11-21 07:57:12 +00005913 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005914 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005915 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005916
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005917 // Overloaded operators other than operator() cannot be variadic.
5918 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005919 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005920 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005921 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005922 }
5923
5924 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005925 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5926 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005927 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005928 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005929 }
5930
5931 // C++ [over.inc]p1:
5932 // The user-defined function called operator++ implements the
5933 // prefix and postfix ++ operator. If this function is a member
5934 // function with no parameters, or a non-member function with one
5935 // parameter of class or enumeration type, it defines the prefix
5936 // increment operator ++ for objects of that type. If the function
5937 // is a member function with one parameter (which shall be of type
5938 // int) or a non-member function with two parameters (the second
5939 // of which shall be of type int), it defines the postfix
5940 // increment operator ++ for objects of that type.
5941 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5942 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5943 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005944 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005945 ParamIsInt = BT->getKind() == BuiltinType::Int;
5946
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005947 if (!ParamIsInt)
5948 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005949 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005950 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005951 }
5952
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005953 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005954}
Chris Lattner5a003a42008-12-17 07:09:26 +00005955
Sean Hunta6c058d2010-01-13 09:01:02 +00005956/// CheckLiteralOperatorDeclaration - Check whether the declaration
5957/// of this literal operator function is well-formed. If so, returns
5958/// false; otherwise, emits appropriate diagnostics and returns true.
5959bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5960 DeclContext *DC = FnDecl->getDeclContext();
5961 Decl::Kind Kind = DC->getDeclKind();
5962 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5963 Kind != Decl::LinkageSpec) {
5964 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5965 << FnDecl->getDeclName();
5966 return true;
5967 }
5968
5969 bool Valid = false;
5970
Sean Hunt216c2782010-04-07 23:11:06 +00005971 // template <char...> type operator "" name() is the only valid template
5972 // signature, and the only valid signature with no parameters.
5973 if (FnDecl->param_size() == 0) {
5974 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5975 // Must have only one template parameter
5976 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5977 if (Params->size() == 1) {
5978 NonTypeTemplateParmDecl *PmDecl =
5979 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005980
Sean Hunt216c2782010-04-07 23:11:06 +00005981 // The template parameter must be a char parameter pack.
5982 // FIXME: This test will always fail because non-type parameter packs
5983 // have not been implemented.
5984 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5985 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5986 Valid = true;
5987 }
5988 }
5989 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005990 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005991 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5992
Sean Hunta6c058d2010-01-13 09:01:02 +00005993 QualType T = (*Param)->getType();
5994
Sean Hunt30019c02010-04-07 22:57:35 +00005995 // unsigned long long int, long double, and any character type are allowed
5996 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005997 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5998 Context.hasSameType(T, Context.LongDoubleTy) ||
5999 Context.hasSameType(T, Context.CharTy) ||
6000 Context.hasSameType(T, Context.WCharTy) ||
6001 Context.hasSameType(T, Context.Char16Ty) ||
6002 Context.hasSameType(T, Context.Char32Ty)) {
6003 if (++Param == FnDecl->param_end())
6004 Valid = true;
6005 goto FinishedParams;
6006 }
6007
Sean Hunt30019c02010-04-07 22:57:35 +00006008 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006009 const PointerType *PT = T->getAs<PointerType>();
6010 if (!PT)
6011 goto FinishedParams;
6012 T = PT->getPointeeType();
6013 if (!T.isConstQualified())
6014 goto FinishedParams;
6015 T = T.getUnqualifiedType();
6016
6017 // Move on to the second parameter;
6018 ++Param;
6019
6020 // If there is no second parameter, the first must be a const char *
6021 if (Param == FnDecl->param_end()) {
6022 if (Context.hasSameType(T, Context.CharTy))
6023 Valid = true;
6024 goto FinishedParams;
6025 }
6026
6027 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6028 // are allowed as the first parameter to a two-parameter function
6029 if (!(Context.hasSameType(T, Context.CharTy) ||
6030 Context.hasSameType(T, Context.WCharTy) ||
6031 Context.hasSameType(T, Context.Char16Ty) ||
6032 Context.hasSameType(T, Context.Char32Ty)))
6033 goto FinishedParams;
6034
6035 // The second and final parameter must be an std::size_t
6036 T = (*Param)->getType().getUnqualifiedType();
6037 if (Context.hasSameType(T, Context.getSizeType()) &&
6038 ++Param == FnDecl->param_end())
6039 Valid = true;
6040 }
6041
6042 // FIXME: This diagnostic is absolutely terrible.
6043FinishedParams:
6044 if (!Valid) {
6045 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6046 << FnDecl->getDeclName();
6047 return true;
6048 }
6049
6050 return false;
6051}
6052
Douglas Gregor074149e2009-01-05 19:45:36 +00006053/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6054/// linkage specification, including the language and (if present)
6055/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6056/// the location of the language string literal, which is provided
6057/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6058/// the '{' brace. Otherwise, this linkage specification does not
6059/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006060Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6061 SourceLocation LangLoc,
6062 llvm::StringRef Lang,
6063 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006064 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006065 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006066 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006067 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006068 Language = LinkageSpecDecl::lang_cxx;
6069 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006070 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006071 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006072 }
Mike Stump1eb44332009-09-09 15:08:12 +00006073
Chris Lattnercc98eac2008-12-17 07:13:27 +00006074 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006075
Douglas Gregor074149e2009-01-05 19:45:36 +00006076 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006077 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006078 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006079 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006080 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006081 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006082}
6083
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006084/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006085/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6086/// valid, it's the position of the closing '}' brace in a linkage
6087/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006088Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6089 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006090 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006091 if (LinkageSpec)
6092 PopDeclContext();
6093 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006094}
6095
Douglas Gregord308e622009-05-18 20:51:54 +00006096/// \brief Perform semantic analysis for the variable declaration that
6097/// occurs within a C++ catch clause, returning the newly-created
6098/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006099VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006100 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006101 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006102 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006103 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006104 QualType ExDeclType = TInfo->getType();
6105
Sebastian Redl4b07b292008-12-22 19:15:10 +00006106 // Arrays and functions decay.
6107 if (ExDeclType->isArrayType())
6108 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6109 else if (ExDeclType->isFunctionType())
6110 ExDeclType = Context.getPointerType(ExDeclType);
6111
6112 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6113 // The exception-declaration shall not denote a pointer or reference to an
6114 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006115 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006116 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006117 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006118 Invalid = true;
6119 }
Douglas Gregord308e622009-05-18 20:51:54 +00006120
Douglas Gregora2762912010-03-08 01:47:36 +00006121 // GCC allows catching pointers and references to incomplete types
6122 // as an extension; so do we, but we warn by default.
6123
Sebastian Redl4b07b292008-12-22 19:15:10 +00006124 QualType BaseType = ExDeclType;
6125 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006126 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006127 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006128 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006129 BaseType = Ptr->getPointeeType();
6130 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006131 DK = diag::ext_catch_incomplete_ptr;
6132 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006133 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006134 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006135 BaseType = Ref->getPointeeType();
6136 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006137 DK = diag::ext_catch_incomplete_ref;
6138 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006139 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006140 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006141 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6142 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006143 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006144
Mike Stump1eb44332009-09-09 15:08:12 +00006145 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006146 RequireNonAbstractType(Loc, ExDeclType,
6147 diag::err_abstract_type_in_decl,
6148 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006149 Invalid = true;
6150
John McCall5a180392010-07-24 00:37:23 +00006151 // Only the non-fragile NeXT runtime currently supports C++ catches
6152 // of ObjC types, and no runtime supports catching ObjC types by value.
6153 if (!Invalid && getLangOptions().ObjC1) {
6154 QualType T = ExDeclType;
6155 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6156 T = RT->getPointeeType();
6157
6158 if (T->isObjCObjectType()) {
6159 Diag(Loc, diag::err_objc_object_catch);
6160 Invalid = true;
6161 } else if (T->isObjCObjectPointerType()) {
6162 if (!getLangOptions().NeXTRuntime) {
6163 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6164 Invalid = true;
6165 } else if (!getLangOptions().ObjCNonFragileABI) {
6166 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6167 Invalid = true;
6168 }
6169 }
6170 }
6171
Mike Stump1eb44332009-09-09 15:08:12 +00006172 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006173 Name, ExDeclType, TInfo, SC_None,
6174 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006175 ExDecl->setExceptionVariable(true);
6176
Douglas Gregor6d182892010-03-05 23:38:39 +00006177 if (!Invalid) {
6178 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6179 // C++ [except.handle]p16:
6180 // The object declared in an exception-declaration or, if the
6181 // exception-declaration does not specify a name, a temporary (12.2) is
6182 // copy-initialized (8.5) from the exception object. [...]
6183 // The object is destroyed when the handler exits, after the destruction
6184 // of any automatic objects initialized within the handler.
6185 //
6186 // We just pretend to initialize the object with itself, then make sure
6187 // it can be destroyed later.
6188 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6189 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006190 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006191 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6192 SourceLocation());
6193 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006194 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006195 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006196 if (Result.isInvalid())
6197 Invalid = true;
6198 else
6199 FinalizeVarWithDestructor(ExDecl, RecordTy);
6200 }
6201 }
6202
Douglas Gregord308e622009-05-18 20:51:54 +00006203 if (Invalid)
6204 ExDecl->setInvalidDecl();
6205
6206 return ExDecl;
6207}
6208
6209/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6210/// handler.
John McCalld226f652010-08-21 09:40:31 +00006211Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006212 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006213 bool Invalid = D.isInvalidType();
6214
6215 // Check for unexpanded parameter packs.
6216 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6217 UPPC_ExceptionType)) {
6218 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6219 D.getIdentifierLoc());
6220 Invalid = true;
6221 }
6222
John McCallbf1a0282010-06-04 23:28:52 +00006223 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006224
Sebastian Redl4b07b292008-12-22 19:15:10 +00006225 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006226 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006227 LookupOrdinaryName,
6228 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006229 // The scope should be freshly made just for us. There is just no way
6230 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006231 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006232 if (PrevDecl->isTemplateParameter()) {
6233 // Maybe we will complain about the shadowed template parameter.
6234 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006235 }
6236 }
6237
Chris Lattnereaaebc72009-04-25 08:06:05 +00006238 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006239 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6240 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006241 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006242 }
6243
Douglas Gregor83cb9422010-09-09 17:09:21 +00006244 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006245 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006246 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006247
Chris Lattnereaaebc72009-04-25 08:06:05 +00006248 if (Invalid)
6249 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006250
Sebastian Redl4b07b292008-12-22 19:15:10 +00006251 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006252 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006253 PushOnScopeChains(ExDecl, S);
6254 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006255 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006256
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006257 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006258 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006259}
Anders Carlssonfb311762009-03-14 00:25:26 +00006260
John McCalld226f652010-08-21 09:40:31 +00006261Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006262 Expr *AssertExpr,
6263 Expr *AssertMessageExpr_) {
6264 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006265
Anders Carlssonc3082412009-03-14 00:33:21 +00006266 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6267 llvm::APSInt Value(32);
6268 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6269 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6270 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006271 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006272 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006273
Anders Carlssonc3082412009-03-14 00:33:21 +00006274 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006275 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006276 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006277 }
6278 }
Mike Stump1eb44332009-09-09 15:08:12 +00006279
Douglas Gregor399ad972010-12-15 23:55:21 +00006280 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6281 return 0;
6282
Mike Stump1eb44332009-09-09 15:08:12 +00006283 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006284 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006285
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006286 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006287 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006288}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006289
Douglas Gregor1d869352010-04-07 16:53:43 +00006290/// \brief Perform semantic analysis of the given friend type declaration.
6291///
6292/// \returns A friend declaration that.
6293FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6294 TypeSourceInfo *TSInfo) {
6295 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6296
6297 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006298 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006299
Douglas Gregor06245bf2010-04-07 17:57:12 +00006300 if (!getLangOptions().CPlusPlus0x) {
6301 // C++03 [class.friend]p2:
6302 // An elaborated-type-specifier shall be used in a friend declaration
6303 // for a class.*
6304 //
6305 // * The class-key of the elaborated-type-specifier is required.
6306 if (!ActiveTemplateInstantiations.empty()) {
6307 // Do not complain about the form of friend template types during
6308 // template instantiation; we will already have complained when the
6309 // template was declared.
6310 } else if (!T->isElaboratedTypeSpecifier()) {
6311 // If we evaluated the type to a record type, suggest putting
6312 // a tag in front.
6313 if (const RecordType *RT = T->getAs<RecordType>()) {
6314 RecordDecl *RD = RT->getDecl();
6315
6316 std::string InsertionText = std::string(" ") + RD->getKindName();
6317
6318 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6319 << (unsigned) RD->getTagKind()
6320 << T
6321 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6322 InsertionText);
6323 } else {
6324 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6325 << T
6326 << SourceRange(FriendLoc, TypeRange.getEnd());
6327 }
6328 } else if (T->getAs<EnumType>()) {
6329 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006330 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006331 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006332 }
6333 }
6334
Douglas Gregor06245bf2010-04-07 17:57:12 +00006335 // C++0x [class.friend]p3:
6336 // If the type specifier in a friend declaration designates a (possibly
6337 // cv-qualified) class type, that class is declared as a friend; otherwise,
6338 // the friend declaration is ignored.
6339
6340 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6341 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006342
6343 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6344}
6345
John McCall9a34edb2010-10-19 01:40:49 +00006346/// Handle a friend tag declaration where the scope specifier was
6347/// templated.
6348Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6349 unsigned TagSpec, SourceLocation TagLoc,
6350 CXXScopeSpec &SS,
6351 IdentifierInfo *Name, SourceLocation NameLoc,
6352 AttributeList *Attr,
6353 MultiTemplateParamsArg TempParamLists) {
6354 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6355
6356 bool isExplicitSpecialization = false;
6357 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6358 bool Invalid = false;
6359
6360 if (TemplateParameterList *TemplateParams
6361 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6362 TempParamLists.get(),
6363 TempParamLists.size(),
6364 /*friend*/ true,
6365 isExplicitSpecialization,
6366 Invalid)) {
6367 --NumMatchedTemplateParamLists;
6368
6369 if (TemplateParams->size() > 0) {
6370 // This is a declaration of a class template.
6371 if (Invalid)
6372 return 0;
6373
6374 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6375 SS, Name, NameLoc, Attr,
6376 TemplateParams, AS_public).take();
6377 } else {
6378 // The "template<>" header is extraneous.
6379 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6380 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6381 isExplicitSpecialization = true;
6382 }
6383 }
6384
6385 if (Invalid) return 0;
6386
6387 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6388
6389 bool isAllExplicitSpecializations = true;
6390 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6391 if (TempParamLists.get()[I]->size()) {
6392 isAllExplicitSpecializations = false;
6393 break;
6394 }
6395 }
6396
6397 // FIXME: don't ignore attributes.
6398
6399 // If it's explicit specializations all the way down, just forget
6400 // about the template header and build an appropriate non-templated
6401 // friend. TODO: for source fidelity, remember the headers.
6402 if (isAllExplicitSpecializations) {
6403 ElaboratedTypeKeyword Keyword
6404 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6405 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6406 TagLoc, SS.getRange(), NameLoc);
6407 if (T.isNull())
6408 return 0;
6409
6410 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6411 if (isa<DependentNameType>(T)) {
6412 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6413 TL.setKeywordLoc(TagLoc);
6414 TL.setQualifierRange(SS.getRange());
6415 TL.setNameLoc(NameLoc);
6416 } else {
6417 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6418 TL.setKeywordLoc(TagLoc);
6419 TL.setQualifierRange(SS.getRange());
6420 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6421 }
6422
6423 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6424 TSI, FriendLoc);
6425 Friend->setAccess(AS_public);
6426 CurContext->addDecl(Friend);
6427 return Friend;
6428 }
6429
6430 // Handle the case of a templated-scope friend class. e.g.
6431 // template <class T> class A<T>::B;
6432 // FIXME: we don't support these right now.
6433 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6434 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6435 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6436 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6437 TL.setKeywordLoc(TagLoc);
6438 TL.setQualifierRange(SS.getRange());
6439 TL.setNameLoc(NameLoc);
6440
6441 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6442 TSI, FriendLoc);
6443 Friend->setAccess(AS_public);
6444 Friend->setUnsupportedFriend(true);
6445 CurContext->addDecl(Friend);
6446 return Friend;
6447}
6448
6449
John McCalldd4a3b02009-09-16 22:47:08 +00006450/// Handle a friend type declaration. This works in tandem with
6451/// ActOnTag.
6452///
6453/// Notes on friend class templates:
6454///
6455/// We generally treat friend class declarations as if they were
6456/// declaring a class. So, for example, the elaborated type specifier
6457/// in a friend declaration is required to obey the restrictions of a
6458/// class-head (i.e. no typedefs in the scope chain), template
6459/// parameters are required to match up with simple template-ids, &c.
6460/// However, unlike when declaring a template specialization, it's
6461/// okay to refer to a template specialization without an empty
6462/// template parameter declaration, e.g.
6463/// friend class A<T>::B<unsigned>;
6464/// We permit this as a special case; if there are any template
6465/// parameters present at all, require proper matching, i.e.
6466/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006467Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006468 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006469 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006470
6471 assert(DS.isFriendSpecified());
6472 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6473
John McCalldd4a3b02009-09-16 22:47:08 +00006474 // Try to convert the decl specifier to a type. This works for
6475 // friend templates because ActOnTag never produces a ClassTemplateDecl
6476 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006477 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006478 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6479 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006480 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006481 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006482
Douglas Gregor6ccab972010-12-16 01:14:37 +00006483 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6484 return 0;
6485
John McCalldd4a3b02009-09-16 22:47:08 +00006486 // This is definitely an error in C++98. It's probably meant to
6487 // be forbidden in C++0x, too, but the specification is just
6488 // poorly written.
6489 //
6490 // The problem is with declarations like the following:
6491 // template <T> friend A<T>::foo;
6492 // where deciding whether a class C is a friend or not now hinges
6493 // on whether there exists an instantiation of A that causes
6494 // 'foo' to equal C. There are restrictions on class-heads
6495 // (which we declare (by fiat) elaborated friend declarations to
6496 // be) that makes this tractable.
6497 //
6498 // FIXME: handle "template <> friend class A<T>;", which
6499 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006500 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006501 Diag(Loc, diag::err_tagless_friend_type_template)
6502 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006503 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006504 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006505
John McCall02cace72009-08-28 07:59:38 +00006506 // C++98 [class.friend]p1: A friend of a class is a function
6507 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006508 // This is fixed in DR77, which just barely didn't make the C++03
6509 // deadline. It's also a very silly restriction that seriously
6510 // affects inner classes and which nobody else seems to implement;
6511 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006512 //
6513 // But note that we could warn about it: it's always useless to
6514 // friend one of your own members (it's not, however, worthless to
6515 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006516
John McCalldd4a3b02009-09-16 22:47:08 +00006517 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006518 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006519 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006520 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006521 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006522 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006523 DS.getFriendSpecLoc());
6524 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006525 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6526
6527 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006528 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006529
John McCalldd4a3b02009-09-16 22:47:08 +00006530 D->setAccess(AS_public);
6531 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006532
John McCalld226f652010-08-21 09:40:31 +00006533 return D;
John McCall02cace72009-08-28 07:59:38 +00006534}
6535
John McCall337ec3d2010-10-12 23:13:28 +00006536Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6537 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006538 const DeclSpec &DS = D.getDeclSpec();
6539
6540 assert(DS.isFriendSpecified());
6541 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6542
6543 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006544 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6545 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006546
6547 // C++ [class.friend]p1
6548 // A friend of a class is a function or class....
6549 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006550 // It *doesn't* see through dependent types, which is correct
6551 // according to [temp.arg.type]p3:
6552 // If a declaration acquires a function type through a
6553 // type dependent on a template-parameter and this causes
6554 // a declaration that does not use the syntactic form of a
6555 // function declarator to have a function type, the program
6556 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006557 if (!T->isFunctionType()) {
6558 Diag(Loc, diag::err_unexpected_friend);
6559
6560 // It might be worthwhile to try to recover by creating an
6561 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006562 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006563 }
6564
6565 // C++ [namespace.memdef]p3
6566 // - If a friend declaration in a non-local class first declares a
6567 // class or function, the friend class or function is a member
6568 // of the innermost enclosing namespace.
6569 // - The name of the friend is not found by simple name lookup
6570 // until a matching declaration is provided in that namespace
6571 // scope (either before or after the class declaration granting
6572 // friendship).
6573 // - If a friend function is called, its name may be found by the
6574 // name lookup that considers functions from namespaces and
6575 // classes associated with the types of the function arguments.
6576 // - When looking for a prior declaration of a class or a function
6577 // declared as a friend, scopes outside the innermost enclosing
6578 // namespace scope are not considered.
6579
John McCall337ec3d2010-10-12 23:13:28 +00006580 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006581 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6582 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006583 assert(Name);
6584
Douglas Gregor6ccab972010-12-16 01:14:37 +00006585 // Check for unexpanded parameter packs.
6586 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6587 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6588 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6589 return 0;
6590
John McCall67d1a672009-08-06 02:15:43 +00006591 // The context we found the declaration in, or in which we should
6592 // create the declaration.
6593 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006594 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006595 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006596 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006597
John McCall337ec3d2010-10-12 23:13:28 +00006598 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006599
John McCall337ec3d2010-10-12 23:13:28 +00006600 // There are four cases here.
6601 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006602 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006603 // there as appropriate.
6604 // Recover from invalid scope qualifiers as if they just weren't there.
6605 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006606 // C++0x [namespace.memdef]p3:
6607 // If the name in a friend declaration is neither qualified nor
6608 // a template-id and the declaration is a function or an
6609 // elaborated-type-specifier, the lookup to determine whether
6610 // the entity has been previously declared shall not consider
6611 // any scopes outside the innermost enclosing namespace.
6612 // C++0x [class.friend]p11:
6613 // If a friend declaration appears in a local class and the name
6614 // specified is an unqualified name, a prior declaration is
6615 // looked up without considering scopes that are outside the
6616 // innermost enclosing non-class scope. For a friend function
6617 // declaration, if there is no prior declaration, the program is
6618 // ill-formed.
6619 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006620 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006621
John McCall29ae6e52010-10-13 05:45:15 +00006622 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006623 DC = CurContext;
6624 while (true) {
6625 // Skip class contexts. If someone can cite chapter and verse
6626 // for this behavior, that would be nice --- it's what GCC and
6627 // EDG do, and it seems like a reasonable intent, but the spec
6628 // really only says that checks for unqualified existing
6629 // declarations should stop at the nearest enclosing namespace,
6630 // not that they should only consider the nearest enclosing
6631 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006632 while (DC->isRecord())
6633 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006634
John McCall68263142009-11-18 22:49:29 +00006635 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006636
6637 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006638 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006639 break;
John McCall29ae6e52010-10-13 05:45:15 +00006640
John McCall8a407372010-10-14 22:22:28 +00006641 if (isTemplateId) {
6642 if (isa<TranslationUnitDecl>(DC)) break;
6643 } else {
6644 if (DC->isFileContext()) break;
6645 }
John McCall67d1a672009-08-06 02:15:43 +00006646 DC = DC->getParent();
6647 }
6648
6649 // C++ [class.friend]p1: A friend of a class is a function or
6650 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006651 // C++0x changes this for both friend types and functions.
6652 // Most C++ 98 compilers do seem to give an error here, so
6653 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006654 if (!Previous.empty() && DC->Equals(CurContext)
6655 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006656 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006657
John McCall380aaa42010-10-13 06:22:15 +00006658 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006659
John McCall337ec3d2010-10-12 23:13:28 +00006660 // - There's a non-dependent scope specifier, in which case we
6661 // compute it and do a previous lookup there for a function
6662 // or function template.
6663 } else if (!SS.getScopeRep()->isDependent()) {
6664 DC = computeDeclContext(SS);
6665 if (!DC) return 0;
6666
6667 if (RequireCompleteDeclContext(SS, DC)) return 0;
6668
6669 LookupQualifiedName(Previous, DC);
6670
6671 // Ignore things found implicitly in the wrong scope.
6672 // TODO: better diagnostics for this case. Suggesting the right
6673 // qualified scope would be nice...
6674 LookupResult::Filter F = Previous.makeFilter();
6675 while (F.hasNext()) {
6676 NamedDecl *D = F.next();
6677 if (!DC->InEnclosingNamespaceSetOf(
6678 D->getDeclContext()->getRedeclContext()))
6679 F.erase();
6680 }
6681 F.done();
6682
6683 if (Previous.empty()) {
6684 D.setInvalidType();
6685 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6686 return 0;
6687 }
6688
6689 // C++ [class.friend]p1: A friend of a class is a function or
6690 // class that is not a member of the class . . .
6691 if (DC->Equals(CurContext))
6692 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6693
6694 // - There's a scope specifier that does not match any template
6695 // parameter lists, in which case we use some arbitrary context,
6696 // create a method or method template, and wait for instantiation.
6697 // - There's a scope specifier that does match some template
6698 // parameter lists, which we don't handle right now.
6699 } else {
6700 DC = CurContext;
6701 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006702 }
6703
John McCall29ae6e52010-10-13 05:45:15 +00006704 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006705 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006706 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6707 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6708 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006709 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006710 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6711 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006712 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006713 }
John McCall67d1a672009-08-06 02:15:43 +00006714 }
6715
Douglas Gregor182ddf02009-09-28 00:08:27 +00006716 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006717 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006718 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006719 IsDefinition,
6720 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006721 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006722
Douglas Gregor182ddf02009-09-28 00:08:27 +00006723 assert(ND->getDeclContext() == DC);
6724 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006725
John McCallab88d972009-08-31 22:39:49 +00006726 // Add the function declaration to the appropriate lookup tables,
6727 // adjusting the redeclarations list as necessary. We don't
6728 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006729 //
John McCallab88d972009-08-31 22:39:49 +00006730 // Also update the scope-based lookup if the target context's
6731 // lookup context is in lexical scope.
6732 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006733 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006734 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006735 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006736 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006737 }
John McCall02cace72009-08-28 07:59:38 +00006738
6739 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006740 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006741 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006742 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006743 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006744
John McCall337ec3d2010-10-12 23:13:28 +00006745 if (ND->isInvalidDecl())
6746 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006747 else {
6748 FunctionDecl *FD;
6749 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6750 FD = FTD->getTemplatedDecl();
6751 else
6752 FD = cast<FunctionDecl>(ND);
6753
6754 // Mark templated-scope function declarations as unsupported.
6755 if (FD->getNumTemplateParameterLists())
6756 FrD->setUnsupportedFriend(true);
6757 }
John McCall337ec3d2010-10-12 23:13:28 +00006758
John McCalld226f652010-08-21 09:40:31 +00006759 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006760}
6761
John McCalld226f652010-08-21 09:40:31 +00006762void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6763 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006764
Sebastian Redl50de12f2009-03-24 22:27:57 +00006765 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6766 if (!Fn) {
6767 Diag(DelLoc, diag::err_deleted_non_function);
6768 return;
6769 }
6770 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6771 Diag(DelLoc, diag::err_deleted_decl_not_first);
6772 Diag(Prev->getLocation(), diag::note_previous_declaration);
6773 // If the declaration wasn't the first, we delete the function anyway for
6774 // recovery.
6775 }
6776 Fn->setDeleted();
6777}
Sebastian Redl13e88542009-04-27 21:33:24 +00006778
6779static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6780 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6781 ++CI) {
6782 Stmt *SubStmt = *CI;
6783 if (!SubStmt)
6784 continue;
6785 if (isa<ReturnStmt>(SubStmt))
6786 Self.Diag(SubStmt->getSourceRange().getBegin(),
6787 diag::err_return_in_constructor_handler);
6788 if (!isa<Expr>(SubStmt))
6789 SearchForReturnInStmt(Self, SubStmt);
6790 }
6791}
6792
6793void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6794 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6795 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6796 SearchForReturnInStmt(*this, Handler);
6797 }
6798}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006799
Mike Stump1eb44332009-09-09 15:08:12 +00006800bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006801 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006802 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6803 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006804
Chandler Carruth73857792010-02-15 11:53:20 +00006805 if (Context.hasSameType(NewTy, OldTy) ||
6806 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006807 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006808
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006809 // Check if the return types are covariant
6810 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006811
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006812 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006813 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6814 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006815 NewClassTy = NewPT->getPointeeType();
6816 OldClassTy = OldPT->getPointeeType();
6817 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006818 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6819 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6820 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6821 NewClassTy = NewRT->getPointeeType();
6822 OldClassTy = OldRT->getPointeeType();
6823 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006824 }
6825 }
Mike Stump1eb44332009-09-09 15:08:12 +00006826
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006827 // The return types aren't either both pointers or references to a class type.
6828 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006829 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006830 diag::err_different_return_type_for_overriding_virtual_function)
6831 << New->getDeclName() << NewTy << OldTy;
6832 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006833
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006834 return true;
6835 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006836
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006837 // C++ [class.virtual]p6:
6838 // If the return type of D::f differs from the return type of B::f, the
6839 // class type in the return type of D::f shall be complete at the point of
6840 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006841 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6842 if (!RT->isBeingDefined() &&
6843 RequireCompleteType(New->getLocation(), NewClassTy,
6844 PDiag(diag::err_covariant_return_incomplete)
6845 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006846 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006847 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006848
Douglas Gregora4923eb2009-11-16 21:35:15 +00006849 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006850 // Check if the new class derives from the old class.
6851 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6852 Diag(New->getLocation(),
6853 diag::err_covariant_return_not_derived)
6854 << New->getDeclName() << NewTy << OldTy;
6855 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6856 return true;
6857 }
Mike Stump1eb44332009-09-09 15:08:12 +00006858
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006859 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006860 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006861 diag::err_covariant_return_inaccessible_base,
6862 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6863 // FIXME: Should this point to the return type?
6864 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006865 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6866 return true;
6867 }
6868 }
Mike Stump1eb44332009-09-09 15:08:12 +00006869
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006870 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006871 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006872 Diag(New->getLocation(),
6873 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006874 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006875 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6876 return true;
6877 };
Mike Stump1eb44332009-09-09 15:08:12 +00006878
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006879
6880 // The new class type must have the same or less qualifiers as the old type.
6881 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6882 Diag(New->getLocation(),
6883 diag::err_covariant_return_type_class_type_more_qualified)
6884 << New->getDeclName() << NewTy << OldTy;
6885 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6886 return true;
6887 };
Mike Stump1eb44332009-09-09 15:08:12 +00006888
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006889 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006890}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006891
Sean Huntbbd37c62009-11-21 08:43:09 +00006892bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6893 const CXXMethodDecl *Old)
6894{
6895 if (Old->hasAttr<FinalAttr>()) {
6896 Diag(New->getLocation(), diag::err_final_function_overridden)
6897 << New->getDeclName();
6898 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6899 return true;
6900 }
6901
6902 return false;
6903}
6904
Douglas Gregor4ba31362009-12-01 17:24:26 +00006905/// \brief Mark the given method pure.
6906///
6907/// \param Method the method to be marked pure.
6908///
6909/// \param InitRange the source range that covers the "0" initializer.
6910bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6911 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6912 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006913 return false;
6914 }
6915
6916 if (!Method->isInvalidDecl())
6917 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6918 << Method->getDeclName() << InitRange;
6919 return true;
6920}
6921
John McCall731ad842009-12-19 09:28:58 +00006922/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6923/// an initializer for the out-of-line declaration 'Dcl'. The scope
6924/// is a fresh scope pushed for just this purpose.
6925///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006926/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6927/// static data member of class X, names should be looked up in the scope of
6928/// class X.
John McCalld226f652010-08-21 09:40:31 +00006929void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006930 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006931 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006932
John McCall731ad842009-12-19 09:28:58 +00006933 // We should only get called for declarations with scope specifiers, like:
6934 // int foo::bar;
6935 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006936 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006937}
6938
6939/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006940/// initializer for the out-of-line declaration 'D'.
6941void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006942 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006943 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006944
John McCall731ad842009-12-19 09:28:58 +00006945 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006946 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006947}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006948
6949/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6950/// C++ if/switch/while/for statement.
6951/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006952DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006953 // C++ 6.4p2:
6954 // The declarator shall not specify a function or an array.
6955 // The type-specifier-seq shall not contain typedef and shall not declare a
6956 // new class or enumeration.
6957 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6958 "Parser allowed 'typedef' as storage class of condition decl.");
6959
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006960 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006961 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6962 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006963
6964 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6965 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6966 // would be created and CXXConditionDeclExpr wants a VarDecl.
6967 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6968 << D.getSourceRange();
6969 return DeclResult();
6970 } else if (OwnedTag && OwnedTag->isDefinition()) {
6971 // The type-specifier-seq shall not declare a new class or enumeration.
6972 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6973 }
6974
John McCalld226f652010-08-21 09:40:31 +00006975 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006976 if (!Dcl)
6977 return DeclResult();
6978
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006979 return Dcl;
6980}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006981
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006982void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6983 bool DefinitionRequired) {
6984 // Ignore any vtable uses in unevaluated operands or for classes that do
6985 // not have a vtable.
6986 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6987 CurContext->isDependentContext() ||
6988 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006989 return;
6990
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006991 // Try to insert this class into the map.
6992 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6993 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6994 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6995 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006996 // If we already had an entry, check to see if we are promoting this vtable
6997 // to required a definition. If so, we need to reappend to the VTableUses
6998 // list, since we may have already processed the first entry.
6999 if (DefinitionRequired && !Pos.first->second) {
7000 Pos.first->second = true;
7001 } else {
7002 // Otherwise, we can early exit.
7003 return;
7004 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007005 }
7006
7007 // Local classes need to have their virtual members marked
7008 // immediately. For all other classes, we mark their virtual members
7009 // at the end of the translation unit.
7010 if (Class->isLocalClass())
7011 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007012 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007013 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007014}
7015
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007016bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007017 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007018 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007019
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007020 // Note: The VTableUses vector could grow as a result of marking
7021 // the members of a class as "used", so we check the size each
7022 // time through the loop and prefer indices (with are stable) to
7023 // iterators (which are not).
7024 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007025 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007026 if (!Class)
7027 continue;
7028
7029 SourceLocation Loc = VTableUses[I].second;
7030
7031 // If this class has a key function, but that key function is
7032 // defined in another translation unit, we don't need to emit the
7033 // vtable even though we're using it.
7034 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007035 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007036 switch (KeyFunction->getTemplateSpecializationKind()) {
7037 case TSK_Undeclared:
7038 case TSK_ExplicitSpecialization:
7039 case TSK_ExplicitInstantiationDeclaration:
7040 // The key function is in another translation unit.
7041 continue;
7042
7043 case TSK_ExplicitInstantiationDefinition:
7044 case TSK_ImplicitInstantiation:
7045 // We will be instantiating the key function.
7046 break;
7047 }
7048 } else if (!KeyFunction) {
7049 // If we have a class with no key function that is the subject
7050 // of an explicit instantiation declaration, suppress the
7051 // vtable; it will live with the explicit instantiation
7052 // definition.
7053 bool IsExplicitInstantiationDeclaration
7054 = Class->getTemplateSpecializationKind()
7055 == TSK_ExplicitInstantiationDeclaration;
7056 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7057 REnd = Class->redecls_end();
7058 R != REnd; ++R) {
7059 TemplateSpecializationKind TSK
7060 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7061 if (TSK == TSK_ExplicitInstantiationDeclaration)
7062 IsExplicitInstantiationDeclaration = true;
7063 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7064 IsExplicitInstantiationDeclaration = false;
7065 break;
7066 }
7067 }
7068
7069 if (IsExplicitInstantiationDeclaration)
7070 continue;
7071 }
7072
7073 // Mark all of the virtual members of this class as referenced, so
7074 // that we can build a vtable. Then, tell the AST consumer that a
7075 // vtable for this class is required.
7076 MarkVirtualMembersReferenced(Loc, Class);
7077 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7078 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7079
7080 // Optionally warn if we're emitting a weak vtable.
7081 if (Class->getLinkage() == ExternalLinkage &&
7082 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007083 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007084 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7085 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007086 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007087 VTableUses.clear();
7088
Anders Carlssond6a637f2009-12-07 08:24:59 +00007089 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007090}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007091
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007092void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7093 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007094 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7095 e = RD->method_end(); i != e; ++i) {
7096 CXXMethodDecl *MD = *i;
7097
7098 // C++ [basic.def.odr]p2:
7099 // [...] A virtual member function is used if it is not pure. [...]
7100 if (MD->isVirtual() && !MD->isPure())
7101 MarkDeclarationReferenced(Loc, MD);
7102 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007103
7104 // Only classes that have virtual bases need a VTT.
7105 if (RD->getNumVBases() == 0)
7106 return;
7107
7108 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7109 e = RD->bases_end(); i != e; ++i) {
7110 const CXXRecordDecl *Base =
7111 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007112 if (Base->getNumVBases() == 0)
7113 continue;
7114 MarkVirtualMembersReferenced(Loc, Base);
7115 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007116}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007117
7118/// SetIvarInitializers - This routine builds initialization ASTs for the
7119/// Objective-C implementation whose ivars need be initialized.
7120void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7121 if (!getLangOptions().CPlusPlus)
7122 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007123 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007124 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7125 CollectIvarsToConstructOrDestruct(OID, ivars);
7126 if (ivars.empty())
7127 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007128 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007129 for (unsigned i = 0; i < ivars.size(); i++) {
7130 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007131 if (Field->isInvalidDecl())
7132 continue;
7133
Sean Huntcbb67482011-01-08 20:30:50 +00007134 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007135 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7136 InitializationKind InitKind =
7137 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7138
7139 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007140 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007141 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007142 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007143 // Note, MemberInit could actually come back empty if no initialization
7144 // is required (e.g., because it would call a trivial default constructor)
7145 if (!MemberInit.get() || MemberInit.isInvalid())
7146 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007147
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007148 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007149 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7150 SourceLocation(),
7151 MemberInit.takeAs<Expr>(),
7152 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007153 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007154
7155 // Be sure that the destructor is accessible and is marked as referenced.
7156 if (const RecordType *RecordTy
7157 = Context.getBaseElementType(Field->getType())
7158 ->getAs<RecordType>()) {
7159 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007160 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007161 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7162 CheckDestructorAccess(Field->getLocation(), Destructor,
7163 PDiag(diag::err_access_dtor_ivar)
7164 << Context.getBaseElementType(Field->getType()));
7165 }
7166 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007167 }
7168 ObjCImplementation->setIvarInitializers(Context,
7169 AllToInit.data(), AllToInit.size());
7170 }
7171}