blob: b2749bf6cee4ef2aa175f35a8bce2dff6083b972 [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-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 Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-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 Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-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 Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-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 Gregor752a5952011-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 Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Alexis Hunt96d5c762009-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 Gregore7488b92009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000531
John McCall3696dcb2010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539}
540
Douglas Gregor556877c2008-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 Stump11289f42009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000546BaseResult
John McCall48871652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregorc40290e2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky19b9f952010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000561
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000573}
Douglas Gregor556877c2008-04-13 21:30:24 +0000574
Douglas Gregor463421d2009-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 Gregor29a92472008-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 Gregor9d6290b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-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 Gregor29a92472008-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 Gregor463421d2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-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 Gregorb77af8f2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-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 McCall48871652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000646
John McCalle78aac42010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
John McCalle78aac42010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCall67da35c2010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlssona70cff62010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-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 McCallcf142162010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000712}
713
Douglas Gregor88d292c2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallcf142162010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregor36d1b142009-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 McCall1064d7e2010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-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 Carlssona70cff62010-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 Carlsson7afe4242010-04-24 17:11:09 +0000763 }
John McCall5b0829a2010-02-10 09:31:12 +0000764 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregor36d1b142009-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 Redl7c353682009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregor36d1b142009-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 Kyrtzidised983422008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnarad7340582010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853}
854
Argyrios Kyrtzidised983422008-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 Lattnereb4373d2009-04-12 22:37:57 +0000858/// any.
John McCall48871652010-08-21 09:40:31 +0000859Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000862 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
863 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000864 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000865 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
866 DeclarationName Name = NameInfo.getName();
867 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-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 Kyrtzidised983422008-07-01 10:37:29 +0000873 Expr *BitWidth = static_cast<Expr*>(BW);
874 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000875
John McCallb1cd7da2010-06-04 08:34:12 +0000876 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000877 assert(!DS.isFriendSpecified());
878
John McCallb1cd7da2010-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 McCallba7bf592010-08-24 05:47:05 +0000884 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000885 isFunc = TDType->isFunctionType();
886 }
887
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-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 Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +0000899 case DeclSpec::SCS_mutable:
900 if (isFunc) {
901 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000902 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000903 else
Chris Lattner3b054132008-11-19 05:08:23 +0000904 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Sebastian Redl8071edb2008-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 Redlccdfaba2008-11-14 23:42:31 +0000908 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000909 }
910 break;
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +0000920 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
921 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000922 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000923
924 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000925 if (isInstField) {
Douglas Gregora007d362010-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 Gregor3447e762009-08-20 22:52:58 +0000947 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000948 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000949 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
950 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000951 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000952 } else {
John McCall48871652010-08-21 09:40:31 +0000953 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000954 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000955 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000956 }
Chris Lattnerd26760a2009-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 Gregor212cab32009-03-11 20:22:50 +0000962 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-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 Stump11289f42009-09-09 15:08:12 +0000975 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000976 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerd26760a2009-03-05 23:01:03 +0000979 BitWidth = 0;
980 Member->setInvalidDecl();
981 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000982
983 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor3447e762009-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 Lattner73bf7b42009-03-05 22:45:59 +0000989 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000990
Douglas Gregor92751d42008-11-17 22:58:34 +0000991 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000992
Douglas Gregor0c880302009-03-11 23:00:04 +0000993 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000994 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000995 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000996 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000999 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001000 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001001 }
John McCall48871652010-08-21 09:40:31 +00001002 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001003}
1004
Douglas Gregor15e77a22009-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 Gregore8381c02008-11-05 04:29:56 +00001050/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001051MemInitResult
John McCall48871652010-08-21 09:40:31 +00001052Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001053 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001054 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001055 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001056 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001057 SourceLocation IdLoc,
1058 SourceLocation LParenLoc,
1059 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001060 SourceLocation RParenLoc,
1061 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001062 if (!ConstructorD)
1063 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001065 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001066
1067 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001068 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-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 Lewycky9331ed82010-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 Gregore8381c02008-11-05 04:29:56 +00001087 // mem-initializer-id for the hidden base class may be specified
1088 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001089 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001090 // Look for a member, first.
1091 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001092 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001093 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001094 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001095 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001096
Douglas Gregor44e7df62011-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 Pichetd583da02010-12-04 09:14:42 +00001102 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001103 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001104 }
1105
Francois Pichetd583da02010-12-04 09:14:42 +00001106 // Handle anonymous union case.
1107 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-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 Pichetd583da02010-12-04 09:14:42 +00001113 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1114 NumArgs, IdLoc,
1115 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001116 }
Francois Pichetd583da02010-12-04 09:14:42 +00001117 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001118 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001119 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001120 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001121 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001122
1123 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001124 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-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 McCallda6841b2010-04-09 19:01:14 +00001133 // We don't want access-control diagnostics here.
1134 R.suppressDiagnostics();
1135
Douglas Gregora3b624a2010-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 Gregorbbdf20a2010-04-24 15:35:55 +00001145 BaseType = CheckTypenameType(ETK_None,
1146 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001147 *MemberOrBase, SourceLocation(),
1148 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001149 if (BaseType.isNull())
1150 return true;
1151
Douglas Gregora3b624a2010-01-19 06:46:48 +00001152 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001153 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001154 }
1155 }
1156
Douglas Gregor15e77a22009-12-31 09:10:24 +00001157 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001158 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001159 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1160 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001161 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001162 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001168 << FixItHint::CreateReplacement(R.getNameLoc(),
1169 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001170 Diag(Member->getLocation(), diag::note_previous_decl)
1171 << Member->getDeclName();
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001187 << FixItHint::CreateReplacement(R.getNameLoc(),
1188 R.getLookupName().getAsString());
Douglas Gregor43a08572010-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 Gregor15e77a22009-12-31 09:10:24 +00001197 TyD = Type;
1198 }
1199 }
1200 }
1201
Douglas Gregora3b624a2010-01-19 06:46:48 +00001202 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-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 McCallb5a0d312009-12-21 10:41:20 +00001207 }
1208
Douglas Gregora3b624a2010-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 McCallb5a0d312009-12-21 10:41:20 +00001214
Douglas Gregora3b624a2010-01-19 06:46:48 +00001215 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001216 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001217 }
John McCallb5a0d312009-12-21 10:41:20 +00001218 }
1219 }
Mike Stump11289f42009-09-09 15:08:12 +00001220
John McCallbcd03502009-12-07 02:54:59 +00001221 if (!TInfo)
1222 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001223
John McCallbcd03502009-12-07 02:54:59 +00001224 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001225 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001226}
1227
John McCalle22a04a2009-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 Lewyckya2fb98b2010-06-15 07:32:55 +00001232static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001233 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001234 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001235 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1236
Nick Lewyckya2fb98b2010-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 Carlsson0f7e94f2010-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 Lewycky300524242010-10-06 18:37:39 +00001252 (void)VD;
Anders Carlsson0f7e94f2010-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 McCalle22a04a2009-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 Lewyckya2fb98b2010-06-15 07:32:55 +00001266 const Expr *base = ME->getBase();
John McCalle22a04a2009-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 Kyrtzidis03f0e2b2010-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 McCalle22a04a2009-11-04 23:02:40 +00001284 }
Nick Lewyckya2fb98b2010-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 McCalle22a04a2009-11-04 23:02:40 +00001289 continue;
1290 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001291 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1292 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001293 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001294 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001295}
1296
John McCallfaf5fb42010-08-26 23:41:50 +00001297MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001298Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001299 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001300 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001301 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001302 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1303 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1304 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001305 "Member must be a FieldDecl or IndirectFieldDecl");
1306
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001307 if (Member->isInvalidDecl())
1308 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001309
John McCalle22a04a2009-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 McCallc90f6d72009-11-04 23:13:52 +00001313 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-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 Friedman8e1433b2009-07-29 19:44:27 +00001327 bool HasDependentArg = false;
1328 for (unsigned i = 0; i < NumArgs; i++)
1329 HasDependentArg |= Args[i]->isTypeDependent();
1330
Chandler Carruthd44c3102010-12-06 09:23:57 +00001331 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001332 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-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 Carruthd44c3102010-12-06 09:23:57 +00001335 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1336 RParenLoc);
Douglas Gregor7ae2d772010-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 Carruthd44c3102010-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 McCallacf0ee52010-10-08 02:01:28 +00001351
Chandler Carruthd44c3102010-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 Gregora40433a2010-12-07 00:41:46 +00001365 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-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 Gregor7ae2d772010-01-31 09:12:51 +00001381 }
1382
Chandler Carruthd44c3102010-12-06 09:23:57 +00001383 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001384 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001385 IdLoc, LParenLoc, Init,
1386 RParenLoc);
1387 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001388 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001389 IdLoc, LParenLoc, Init,
1390 RParenLoc);
1391 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001392}
1393
John McCallfaf5fb42010-08-26 23:41:50 +00001394MemInitResult
Alexis Hunt4049b8d2011-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 McCallbcd03502009-12-07 02:54:59 +00001411Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001412 Expr **Args, unsigned NumArgs,
1413 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001414 CXXRecordDecl *ClassDecl,
1415 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001416 bool HasDependentArg = false;
1417 for (unsigned i = 0; i < NumArgs; i++)
1418 HasDependentArg |= Args[i]->isTypeDependent();
1419
Douglas Gregor1c69bf02010-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 Lewycky9331ed82010-11-20 01:29:55 +00001429 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-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 Gregor44e7df62011-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 Gregor1c69bf02010-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) {
Alexis Hunt4049b8d2011-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 Gregor1c69bf02010-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 Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001488 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001489 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1490 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001491
Douglas Gregor7ae2d772010-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 Stump11289f42009-09-09 15:08:12 +00001498
Alexis Hunt1d792652011-01-08 20:30:50 +00001499 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001500 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001501 LParenLoc,
1502 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001503 RParenLoc,
1504 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001505 }
Douglas Gregor7ae2d772010-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 Bagnara1108e7b2010-05-20 10:00:11 +00001513 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-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 Carlsson43c64af2010-04-21 19:52:01 +00001522 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001528 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001529 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001530 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001531 if (BaseInit.isInvalid())
1532 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001533
1534 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-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 Gregora40433a2010-12-07 00:41:46 +00001539 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001551 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001552 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1553 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001554 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001555 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001556 LParenLoc,
1557 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001558 RParenLoc,
1559 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001560 }
1561
Alexis Hunt1d792652011-01-08 20:30:50 +00001562 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001563 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001564 LParenLoc,
1565 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001566 RParenLoc,
1567 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001568}
1569
Anders Carlsson1b00e242010-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 Carlsson6bd91c32010-04-23 02:00:02 +00001578static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001579BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001580 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001581 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001582 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001583 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001584 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001585 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1586 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001587
John McCalldadc5752010-08-24 06:29:42 +00001588 ExprResult BaseInit;
Anders Carlsson1b00e242010-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 McCallfaf5fb42010-08-26 23:41:50 +00001596 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001597 break;
1598 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001599
Anders Carlsson1b00e242010-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 McCall7decc9e2010-11-18 06:31:45 +00001606 Constructor->getLocation(), ParamType,
1607 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001608
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001609 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001610 QualType ArgTy =
1611 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1612 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001613
1614 CXXCastPath BasePath;
1615 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001616 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001617 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001618 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001619
Anders Carlsson1b00e242010-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 McCallfaf5fb42010-08-26 23:41:50 +00001626 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001627 break;
1628 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001629
Anders Carlsson1b00e242010-04-23 03:10:23 +00001630 case IIK_Move:
1631 assert(false && "Unhandled initializer kind!");
1632 }
John McCallb268a282010-08-23 23:25:46 +00001633
Douglas Gregora40433a2010-12-07 00:41:46 +00001634 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001635 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001636 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001637
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001638 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001639 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001640 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1641 SourceLocation()),
1642 BaseSpec->isVirtual(),
1643 SourceLocation(),
1644 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001645 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001646 SourceLocation());
1647
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001648 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001649}
1650
Anders Carlsson3c1db572010-04-23 02:15:47 +00001651static bool
1652BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001653 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001654 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001655 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001656 if (Field->isInvalidDecl())
1657 return true;
1658
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001659 SourceLocation Loc = Constructor->getLocation();
1660
Anders Carlsson423f5d82010-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 McCall7decc9e2010-11-18 06:31:45 +00001667 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-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 McCalldadc5752010-08-24 06:29:42 +00001675 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001676 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-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 Carlsson423f5d82010-04-23 16:04:08 +00001684 return true;
1685
Douglas Gregor94f9a482010-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 McCall8e7d6562010-08-26 03:08:43 +00001707 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001708 IndexVariables.push_back(IterationVar);
1709
1710 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001711 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001712 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-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 McCallb268a282010-08-23 23:25:46 +00001717 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001718 Loc,
John McCallb268a282010-08-23 23:25:46 +00001719 IterationVarRef.take(),
Douglas Gregor94f9a482010-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 McCalldadc5752010-08-24 06:29:42 +00001746 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001747 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001748 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001749 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001750 if (MemberInit.isInvalid())
1751 return true;
1752
1753 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001754 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001755 MemberInit.takeAs<Expr>(), Loc,
1756 IndexVariables.data(),
1757 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001758 return false;
1759 }
1760
Anders Carlsson423f5d82010-04-23 16:04:08 +00001761 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1762
Anders Carlsson3c1db572010-04-23 02:15:47 +00001763 QualType FieldBaseElementType =
1764 SemaRef.Context.getBaseElementType(Field->getType());
1765
Anders Carlsson3c1db572010-04-23 02:15:47 +00001766 if (FieldBaseElementType->isRecordType()) {
1767 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001768 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001769 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001770
1771 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001772 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001773 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001774
Douglas Gregora40433a2010-12-07 00:41:46 +00001775 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001776 if (MemberInit.isInvalid())
1777 return true;
1778
1779 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001780 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001781 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001782 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001783 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001784 return false;
1785 }
Anders Carlssondca6be02010-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 Carlsson3c1db572010-04-23 02:15:47 +00001806
1807 // Nothing to initialize.
1808 CXXMemberInit = 0;
1809 return false;
1810}
John McCallbc83b3f2010-05-20 23:23:51 +00001811
1812namespace {
1813struct BaseAndFieldInfo {
1814 Sema &S;
1815 CXXConstructorDecl *Ctor;
1816 bool AnyErrorsInInits;
1817 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001818 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1819 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-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 Carruth139e9622010-06-30 02:59:29 +00001835 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001836 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001837 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-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 McCallbc83b3f2010-05-20 23:23:51 +00001844 CXXRecordDecl *FieldClassDecl
1845 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-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++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001856 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001857 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-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 Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001862 } else if ((*FA)->isAnonymousStructOrUnion()) {
1863 if (CollectFieldInitializer(Info, Top, *FA))
1864 return true;
Chandler Carruth139e9622010-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 McCallbc83b3f2010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00001890 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001891 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1892 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001893
Francois Pichetd583da02010-12-04 09:14:42 +00001894 if (Init)
1895 Info.AllToInit.push_back(Init);
1896
John McCallbc83b3f2010-05-20 23:23:51 +00001897 return false;
1898}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001899
Eli Friedman9cf6b592009-11-09 19:20:36 +00001900bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001901Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1902 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001903 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001904 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001905 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001906 // Just store the initializers as written, they will be checked during
1907 // instantiation.
1908 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001909 Constructor->setNumCtorInitializers(NumInitializers);
1910 CXXCtorInitializer **baseOrMemberInitializers =
1911 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001912 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001913 NumInitializers * sizeof(CXXCtorInitializer*));
1914 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001915 }
1916
1917 return false;
1918 }
1919
John McCallbc83b3f2010-05-20 23:23:51 +00001920 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001921
Fariborz Jahanian3501bce2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00001924 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001925 if (!ClassDecl)
1926 return true;
1927
Eli Friedman9cf6b592009-11-09 19:20:36 +00001928 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001929
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001930 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001931 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001932
1933 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001934 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001935 else
Francois Pichetd583da02010-12-04 09:14:42 +00001936 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001937 }
1938
Anders Carlsson43c64af2010-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 Carlssondb0a9652010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00001951 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001952 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1953 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001954 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001955 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00001956 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001957 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001958 VBase, IsInheritedVirtualBase,
1959 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001960 HadError = true;
1961 continue;
1962 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001963
John McCallbc83b3f2010-05-20 23:23:51 +00001964 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001965 }
1966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
John McCallbc83b3f2010-05-20 23:23:51 +00001968 // Non-virtual bases.
Anders Carlssondb0a9652010-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 Stump11289f42009-09-09 15:08:12 +00001974
Alexis Hunt1d792652011-01-08 20:30:50 +00001975 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001976 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1977 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001978 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001979 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001981 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001982 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001983 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001984 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001985 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001986
John McCallbc83b3f2010-05-20 23:23:51 +00001987 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001988 }
1989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
John McCallbc83b3f2010-05-20 23:23:51 +00001991 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-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 McCallbc83b3f2010-05-20 23:23:51 +00001999 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002000 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002001 }
Mike Stump11289f42009-09-09 15:08:12 +00002002
John McCallbc83b3f2010-05-20 23:23:51 +00002003 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002004 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002005 Constructor->setNumCtorInitializers(NumInitializers);
2006 CXXCtorInitializer **baseOrMemberInitializers =
2007 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002008 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002009 NumInitializers * sizeof(CXXCtorInitializer*));
2010 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002011
John McCalla6309952010-03-16 21:39:52 +00002012 // Constructors implicitly reference the base and member
2013 // destructors.
2014 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2015 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002016 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002017
2018 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002019}
2020
Eli Friedman952c15d2009-07-21 19:28:10 +00002021static void *GetKeyForTopLevelField(FieldDecl *Field) {
2022 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00002030static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002031 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002032}
2033
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002034static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002035 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002036 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002037 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002038
Eli Friedman952c15d2009-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 Pichetd583da02010-12-04 09:14:42 +00002041 FieldDecl *Field = Member->getAnyMember();
2042
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00002045 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00002055 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
Anders Carlssona942dcd2010-03-30 15:39:27 +00002058 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002059}
2060
Anders Carlssone857b292010-04-02 03:37:03 +00002061static void
2062DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002063 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002064 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002065 unsigned NumInits) {
2066 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002067 return;
Mike Stump11289f42009-09-09 15:08:12 +00002068
Argyrios Kyrtzidis1cb0de12010-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) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002073 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-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 Carlssone0eebb32009-08-27 05:45:01 +00002082 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002083
John McCallbb7b6582010-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 Stump11289f42009-09-09 15:08:12 +00002088
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002089 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2090
John McCallbb7b6582010-04-10 07:37:23 +00002091 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002092 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002093 ClassDecl->vbases_begin(),
2094 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002095 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002096
John McCallbb7b6582010-04-10 07:37:23 +00002097 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002098 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002099 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002100 if (Base->isVirtual())
2101 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002103 }
Mike Stump11289f42009-09-09 15:08:12 +00002104
John McCallbb7b6582010-04-10 07:37:23 +00002105 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2107 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002108 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002109
John McCallbb7b6582010-04-10 07:37:23 +00002110 unsigned NumIdealInits = IdealInitKeys.size();
2111 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002112
Alexis Hunt1d792652011-01-08 20:30:50 +00002113 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002114 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002115 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002116 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00002122 break;
John McCallbb7b6582010-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 Gregoraabdfcb2010-05-20 23:49:34 +00002127 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002128 Sema::SemaDiagnosticBuilder D =
2129 SemaRef.Diag(PrevInit->getSourceLocation(),
2130 diag::warn_initializer_out_of_order);
2131
Francois Pichetd583da02010-12-04 09:14:42 +00002132 if (PrevInit->isAnyMemberInitializer())
2133 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002134 else
2135 D << 1 << PrevInit->getBaseClassInfo()->getType();
2136
Francois Pichetd583da02010-12-04 09:14:42 +00002137 if (Init->isAnyMemberInitializer())
2138 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00002145 break;
John McCallbb7b6582010-04-10 07:37:23 +00002146
2147 assert(IdealIndex != NumIdealInits &&
2148 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002149 }
John McCallbb7b6582010-04-10 07:37:23 +00002150
2151 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002152 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002153}
2154
John McCall23eebd92010-04-10 09:28:51 +00002155namespace {
2156bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002157 CXXCtorInitializer *Init,
2158 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-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 {
John McCall424cec92011-01-19 06:33:43 +00002170 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002171 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
Alexis Hunt1d792652011-01-08 20:30:50 +00002183typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002184typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2185
2186bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002187 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002188 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002189 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-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 Carlssone857b292010-04-02 03:37:03 +00002220/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002221void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-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 McCall48871652010-08-21 09:40:31 +00002231 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002232
2233 if (!Constructor) {
2234 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2235 return;
2236 }
2237
Alexis Hunt1d792652011-01-08 20:30:50 +00002238 CXXCtorInitializer **MemInits =
2239 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-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*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002244 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002245
2246 // Mapping for the inconsistent anonymous-union initializers check.
2247 RedundantUnionMap MemberUnions;
2248
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002249 bool HadError = false;
2250 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002251 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002252
Abramo Bagnara341d7832010-05-26 18:09:23 +00002253 // Set the source order index.
2254 Init->setSourceOrder(i);
2255
Francois Pichetd583da02010-12-04 09:14:42 +00002256 if (Init->isAnyMemberInitializer()) {
2257 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-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 Carlssone857b292010-04-02 03:37:03 +00002265 }
Anders Carlssone857b292010-04-02 03:37:03 +00002266 }
2267
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002268 if (HadError)
2269 return;
2270
Anders Carlssone857b292010-04-02 03:37:03 +00002271 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002272
Alexis Hunt1d792652011-01-08 20:30:50 +00002273 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002274}
2275
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002276void
John McCalla6309952010-03-16 21:39:52 +00002277Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2278 CXXRecordDecl *ClassDecl) {
2279 // Ignore dependent contexts.
2280 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002281 return;
John McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002287
Anders Carlssondee9a302009-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 Jahanian16f94c62010-05-17 18:15:18 +00002292 if (Field->isInvalidDecl())
2293 continue;
Anders Carlssondee9a302009-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 Gregore71edda2010-07-01 22:47:18 +00002304 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002305 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002306 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002307 << Field->getDeclName()
2308 << FieldType);
2309
John McCalla6309952010-03-16 21:39:52 +00002310 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002311 }
2312
John McCall1064d7e2010-03-16 05:22:47 +00002313 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2314
Anders Carlssondee9a302009-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 McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002322 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002323 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002324
2325 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002326 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002327 if (BaseClassDecl->hasTrivialDestructor())
2328 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002329
Douglas Gregore71edda2010-07-01 22:47:18 +00002330 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-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 Gregor89336232010-03-29 23:34:08 +00002334 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002335 << Base->getType()
2336 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002337
John McCalla6309952010-03-16 21:39:52 +00002338 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002339 }
2340
2341 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002342 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2343 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002352 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002354 if (BaseClassDecl->hasTrivialDestructor())
2355 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002356
Douglas Gregore71edda2010-07-01 22:47:18 +00002357 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002358 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002359 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002360 << VBase->getType());
2361
John McCalla6309952010-03-16 21:39:52 +00002362 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002363 }
2364}
2365
John McCall48871652010-08-21 09:40:31 +00002366void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002367 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002368 return;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Mike Stump11289f42009-09-09 15:08:12 +00002370 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002371 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002372 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002373}
2374
Mike Stump11289f42009-09-09 15:08:12 +00002375bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002376 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002377 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002378 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002379 else
John McCall02db245d2010-08-18 09:41:07 +00002380 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002381}
2382
Anders Carlssoneabf7702009-08-27 00:13:57 +00002383bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002384 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002385 if (!getLangOptions().CPlusPlus)
2386 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002387
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002388 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002389 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002390
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002391 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002392 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002393 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002394 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002395
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002396 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002397 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002398 }
Mike Stump11289f42009-09-09 15:08:12 +00002399
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002400 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002401 if (!RT)
2402 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002403
John McCall67da35c2010-02-04 22:26:26 +00002404 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002405
John McCall02db245d2010-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 McCall67da35c2010-02-04 22:26:26 +00002411 return false;
2412
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002413 if (!RD->isAbstract())
2414 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002415
Anders Carlssoneabf7702009-08-27 00:13:57 +00002416 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002417 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002418
John McCall02db245d2010-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 Carlsson576cc6f2009-03-22 20:18:17 +00002425 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002426 return;
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregor4165bd62010-03-23 23:47:56 +00002428 CXXFinalOverriderMap FinalOverriders;
2429 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002430
Anders Carlssona2f74f32010-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 Gregor4165bd62010-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 Stump11289f42009-09-09 15:08:12 +00002446
Douglas Gregor4165bd62010-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 Carlssona2f74f32010-06-03 01:00:02 +00002454 if (!SeenPureMethods.insert(SO->second.front().Method))
2455 continue;
2456
Douglas Gregor4165bd62010-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 Carlsson576cc6f2009-03-22 20:18:17 +00002461 }
2462
2463 if (!PureVirtualClassDiagSet)
2464 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2465 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002466}
2467
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002468namespace {
John McCall02db245d2010-08-18 09:41:07 +00002469struct AbstractUsageInfo {
2470 Sema &S;
2471 CXXRecordDecl *Record;
2472 CanQualType AbstractType;
2473 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002474
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002480
John McCall02db245d2010-08-18 09:41:07 +00002481 void DiagnoseAbstractType() {
2482 if (Invalid) return;
2483 S.DiagnoseAbstractType(Record);
2484 Invalid = true;
2485 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002486
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002503 }
John McCall02db245d2010-08-18 09:41:07 +00002504 }
Mike Stump11289f42009-09-09 15:08:12 +00002505
John McCall02db245d2010-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 Carlssonb57738b2009-03-24 17:23:42 +00002511 }
John McCall02db245d2010-08-18 09:41:07 +00002512 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002513
John McCall02db245d2010-08-18 09:41:07 +00002514 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2515 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2516 }
Mike Stump11289f42009-09-09 15:08:12 +00002517
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002526 }
John McCall02db245d2010-08-18 09:41:07 +00002527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528
John McCall02db245d2010-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 Stump11289f42009-09-09 15:08:12 +00002538
John McCall02db245d2010-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 Carlssonb57738b2009-03-24 17:23:42 +00002557 }
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002628}
2629
Douglas Gregorc99f1552009-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 Gregor0be31a22010-07-02 17:43:08 +00002633void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002634 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002635 return;
2636
John McCall02db245d2010-08-18 09:41:07 +00002637 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2638 AbstractUsageInfo Info(*this, Record);
2639 CheckAbstractClassUsage(Info, Record);
2640 }
Douglas Gregor454a5b62010-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 Kramer659d7fc2010-04-16 17:43:15 +00002652 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-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 Gregor88d292c2010-05-13 16:44:06 +00002665
2666 if (Record->isDynamicClass())
2667 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-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 Pichet783dd6e2010-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 Gregor36c22a22010-10-15 13:21:21 +00002685 break;
2686 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002687 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002688 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002689}
2690
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002691void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002692 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002693 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002694 SourceLocation RBrac,
2695 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002696 if (!TagDecl)
2697 return;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002699 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002700
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002701 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002702 // strict aliasing violation!
2703 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002704 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002705
Douglas Gregor0be31a22010-07-02 17:43:08 +00002706 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002707 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002708}
2709
Douglas Gregor95755162010-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 Gregor3311ed42010-07-01 15:29:53 +00002744 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-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 Gregor05379422008-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 Gregor0be31a22010-07-02 17:43:08 +00002774void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002775 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002776 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002777
Douglas Gregor54be3392010-07-01 17:57:27 +00002778 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002779 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002780
Douglas Gregor330b9cf2010-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 Redlbaad4e72009-01-05 20:52:13 +00002791
Douglas Gregor7454c562010-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 Gregor05379422008-11-03 17:51:48 +00002802}
2803
John McCall48871652010-08-21 09:40:31 +00002804void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-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 Gregore44a2ad2009-05-27 23:11:45 +00002815 return;
2816
Douglas Gregore44a2ad2009-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 McCall48871652010-08-21 09:40:31 +00002822 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002823 IdResolver.AddDecl(Named);
2824 }
2825 }
2826}
2827
John McCall48871652010-08-21 09:40:31 +00002828void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002829 if (!RecordD) return;
2830 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002831 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002832 PushDeclContext(S, Record);
2833}
2834
John McCall48871652010-08-21 09:40:31 +00002835void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002836 if (!RecordD) return;
2837 PopDeclContext();
2838}
2839
Douglas Gregor4d87df52008-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 McCall48871652010-08-21 09:40:31 +00002848void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-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 McCall48871652010-08-21 09:40:31 +00002856void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002857 if (!ParamD)
2858 return;
Mike Stump11289f42009-09-09 15:08:12 +00002859
John McCall48871652010-08-21 09:40:31 +00002860 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +00002867 S->AddDecl(Param);
Douglas Gregor4d87df52008-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 McCall48871652010-08-21 09:40:31 +00002878void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002879 if (!MethodD)
2880 return;
Mike Stump11289f42009-09-09 15:08:12 +00002881
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002882 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002883
John McCall48871652010-08-21 09:40:31 +00002884 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-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 Lattnerb41df4f2009-04-25 08:35:12 +00002890 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2891 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-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 Gregor831c93f2008-11-05 20:51:48 +00002898/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002899/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002900/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-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 McCall8e7d6562010-08-26 03:08:43 +00002905 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002906 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-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 Lattner38378bf2009-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 Gregor831c93f2008-11-05 20:51:48 +00002919 }
John McCall8e7d6562010-08-26 03:08:43 +00002920 if (SC == SC_Static) {
Chris Lattner38378bf2009-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 McCall8e7d6562010-08-26 03:08:43 +00002926 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002927 }
Mike Stump11289f42009-09-09 15:08:12 +00002928
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002929 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002930 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002931 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002932 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2933 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002934 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002935 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2936 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002937 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002938 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2939 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002940 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002941 }
Mike Stump11289f42009-09-09 15:08:12 +00002942
Douglas Gregor831c93f2008-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 Gregor95755162010-07-01 05:10:53 +00002945 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002946 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-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 Lattner38378bf2009-04-25 08:28:21 +00002953 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002954 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002955}
2956
Douglas Gregor4d87df52008-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 Lattnerb41df4f2009-04-25 08:35:12 +00002960void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002961 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002962 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2963 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002964 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-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 Gregorf4d17c42009-03-27 04:38:56 +00002971 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002972 ((Constructor->getNumParams() == 1) ||
2973 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002974 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2975 Constructor->getTemplateSpecializationKind()
2976 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-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 Gregor170512f2009-04-01 23:51:29 +00002980 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002981 const char *ConstRef
2982 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2983 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002984 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002985 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002986
2987 // FIXME: Rather that making the constructor invalid, we should endeavor
2988 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002989 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002990 }
2991 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002992}
2993
John McCalldeb646e2010-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 Carlssonf98849e2009-12-02 17:15:43 +00002997bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-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 Carlssonf98849e2009-12-02 17:15:43 +00003012 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003013 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003014
3015 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003016
3017 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003018 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003019
3020 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003021}
3022
Mike Stump11289f42009-09-09 15:08:12 +00003023static inline bool
Anders Carlsson5e965472009-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 McCall48871652010-08-21 09:40:31 +00003027 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003028}
3029
Douglas Gregor831c93f2008-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 Lattner38378bf2009-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 Gregor95755162010-07-01 05:10:53 +00003036QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003037 StorageClass& SC) {
Douglas Gregor831c93f2008-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 Gregor7861a802009-11-03 01:35:08 +00003043 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003044 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003045 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003046 << DeclaratorType;
Douglas Gregor831c93f2008-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 McCall8e7d6562010-08-26 03:08:43 +00003056 if (SC == SC_Static) {
Chris Lattner38378bf2009-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 Gregor95755162010-07-01 05:10:53 +00003060 << SourceRange(D.getIdentifierLoc())
3061 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3062
John McCall8e7d6562010-08-26 03:08:43 +00003063 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003064 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003065 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-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 Lattner3b054132008-11-19 05:08:23 +00003074 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3075 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3076 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003077 }
Mike Stump11289f42009-09-09 15:08:12 +00003078
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003079 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003080 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003081 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3083 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003084 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003085 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3086 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003087 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003088 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3089 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003090 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003091 }
3092
3093 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003094 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003095 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3096
3097 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003098 FTI.freeArgs();
3099 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003100 }
3101
Mike Stump11289f42009-09-09 15:08:12 +00003102 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003103 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003104 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003105 D.setInvalidType();
3106 }
Douglas Gregor831c93f2008-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 Gregor95755162010-07-01 05:10:53 +00003111 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003112 if (!D.isInvalidType())
3113 return R;
3114
Douglas Gregor95755162010-07-01 05:10:53 +00003115 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-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 Gregor831c93f2008-11-05 20:51:48 +00003120}
3121
Douglas Gregordbc5daf2008-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 Lattnerb41df4f2009-04-25 08:35:12 +00003128void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003129 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003130 // C++ [class.conv.fct]p1:
3131 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003132 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003133 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003134 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-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 McCall8e7d6562010-08-26 03:08:43 +00003140 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003141 }
John McCall212fa2e2010-04-13 00:04:31 +00003142
3143 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3144
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003145 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-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 Lattner3b054132008-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 McCall212fa2e2010-04-13 00:04:31 +00003157 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003158 }
3159
John McCall212fa2e2010-04-13 00:04:31 +00003160 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3161
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003162 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003163 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003164 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3165
3166 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003167 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003168 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003169 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003170 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003171 D.setInvalidType();
3172 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173
John McCall212fa2e2010-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 Gregordbc5daf2008-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 Gregordbc5daf2008-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 Lattnerb41df4f2009-04-25 08:35:12 +00003189 D.setInvalidType();
Douglas Gregordbc5daf2008-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 Lattnerb41df4f2009-04-25 08:35:12 +00003193 D.setInvalidType();
Douglas Gregordbc5daf2008-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 Stump11289f42009-09-09 15:08:12 +00003198 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003199 if (D.isInvalidType())
3200 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003201
Douglas Gregor5fb53972009-01-14 15:45:31 +00003202 // C++0x explicit conversion operators.
3203 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003204 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003205 diag::warn_explicit_conversion_functions)
3206 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003207}
3208
Douglas Gregordbc5daf2008-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 McCall48871652010-08-21 09:40:31 +00003213Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003214 assert(Conversion && "Expected to receive a conversion function declaration");
3215
Douglas Gregor4287b372008-12-12 08:25:50 +00003216 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003217
3218 // Make sure we aren't redeclaring the conversion function.
3219 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-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 Stump87c57ac2009-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 Stump11289f42009-09-09 15:08:12 +00003229 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003230 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003231 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003232 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003233 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3234 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003235 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003236 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003237 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3238 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003239 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003240 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003241 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003242 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003243 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003244 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003245 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003246 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003247 }
3248
Douglas Gregor457104e2010-09-29 04:25:11 +00003249 if (FunctionTemplateDecl *ConversionTemplate
3250 = Conversion->getDescribedFunctionTemplate())
3251 return ConversionTemplate;
3252
John McCall48871652010-08-21 09:40:31 +00003253 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003254}
3255
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003256//===----------------------------------------------------------------------===//
3257// Namespace Handling
3258//===----------------------------------------------------------------------===//
3259
John McCallb1be5232010-08-26 09:15:37 +00003260
3261
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003262/// ActOnStartNamespaceDef - This is called at the start of a namespace
3263/// definition.
John McCall48871652010-08-21 09:40:31 +00003264Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003265 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003266 SourceLocation IdentLoc,
3267 IdentifierInfo *II,
3268 SourceLocation LBrace,
3269 AttributeList *AttrList) {
Douglas Gregor086cae62010-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 Kyrtzidis08114892008-04-27 13:50:30 +00003273 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003274 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003275
3276 Scope *DeclRegionScope = NamespcScope->getParent();
3277
Anders Carlssona7bcade2010-02-07 01:09:23 +00003278 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3279
John McCall2faf32c2010-12-10 02:59:44 +00003280 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3281 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003282
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003283 if (II) {
3284 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-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 Stump11289f42009-09-09 15:08:12 +00003296
Douglas Gregor91f84212008-12-11 16:49:14 +00003297 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3298 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-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 Gregor91f84212008-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 Kyrtzidis08114892008-04-27 13:50:30 +00003313
Mike Stump11289f42009-09-09 15:08:12 +00003314 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003315 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003316 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003317 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003318 }
Douglas Gregor91f84212008-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 Gregor87f54062009-09-15 22:30:29 +00003326 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003327 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-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 Kyrtzidis2d688102010-08-02 07:14:54 +00003330 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-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 Kyrtzidis2d688102010-08-02 07:14:54 +00003333 StdNS->setNextNamespace(Namespc);
3334 StdNS->setLocation(IdentLoc);
3335 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-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 Stump11289f42009-09-09 15:08:12 +00003341 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003342
3343 PushOnScopeChains(Namespc, DeclRegionScope);
3344 } else {
John McCall4fa53422009-10-01 00:25:31 +00003345 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003346 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003347
3348 // Link the anonymous namespace into its parent.
3349 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003350 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-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 Redlb5c2baa2010-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 McCall0db42252009-12-16 02:06:49 +00003376 }
John McCall4fa53422009-10-01 00:25:31 +00003377
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003378 CurContext->addDecl(Namespc);
3379
John McCall4fa53422009-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 McCall0db42252009-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 Kyrtzidis08114892008-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 Stump87c57ac2009-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 Gregor91f84212008-12-11 16:49:14 +00003416 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003417 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003418}
3419
Sebastian Redla6602e92009-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 Kyrtzidis08114892008-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 McCall48871652010-08-21 09:40:31 +00003430void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-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 Friedman570024a2010-08-05 06:57:20 +00003435 if (Namespc->hasAttr<VisibilityAttr>())
3436 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003437}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003438
John McCall28a0cf72010-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 Gregorcdf87022010-06-29 17:53:46 +00003449/// \brief Retrieve the special "std" namespace, which may require us to
3450/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003451NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-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 Kyrtzidis2d688102010-08-02 07:14:54 +00003458 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003459 }
3460
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003461 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003462}
3463
John McCall48871652010-08-21 09:40:31 +00003464Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003465 SourceLocation UsingLoc,
3466 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003467 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003468 SourceLocation IdentLoc,
3469 IdentifierInfo *NamespcName,
3470 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003471 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3472 assert(NamespcName && "Invalid NamespcName.");
3473 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-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 Gregor889ceb72009-02-03 19:21:40 +00003478 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003479
Douglas Gregor889ceb72009-02-03 19:21:40 +00003480 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003481 NestedNameSpecifier *Qualifier = 0;
3482 if (SS.isSet())
3483 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3484
Douglas Gregor34074322009-01-14 22:20:51 +00003485 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003486 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3487 LookupParsedName(R, S, &SS);
3488 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003489 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003490
Douglas Gregorcdf87022010-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 Kyrtzidis4f8e1732010-08-02 07:14:39 +00003497 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-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 Gregorc048c522010-06-29 19:27:42 +00003517 } else {
3518 R.clear();
3519 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003520 }
3521 }
3522 }
3523
John McCall9f3059a2009-10-09 21:13:30 +00003524 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003525 NamedDecl *Named = R.getFoundDecl();
3526 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3527 && "expected namespace decl");
Douglas Gregor889ceb72009-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 Friedman44b83ee2009-08-05 19:21:58 +00003535 // namespace. [Note: in this context, "contains" means "contains
3536 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003537
3538 // Find enclosing context containing both using-directive and
3539 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003540 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003541 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3542 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3543 CommonAncestor = CommonAncestor->getParent();
3544
Sebastian Redla6602e92009-11-23 15:34:23 +00003545 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003546 SS.getRange(),
3547 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003548 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003549 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003550 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003551 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003552 }
3553
Douglas Gregor889ceb72009-02-03 19:21:40 +00003554 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003555 return UDir;
Douglas Gregor889ceb72009-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 Kyrtzidiscfbfe782009-06-30 02:36:12 +00003563 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-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 McCall48871652010-08-21 09:40:31 +00003567 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003568}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003569
Douglas Gregorfec52632009-06-20 00:51:54 +00003570
John McCall48871652010-08-21 09:40:31 +00003571Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-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 Gregorfec52632009-06-20 00:51:54 +00003580 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003581
Douglas Gregor220f4272009-11-04 16:30:06 +00003582 switch (Name.getKind()) {
3583 case UnqualifiedId::IK_Identifier:
3584 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003585 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003586 case UnqualifiedId::IK_ConversionFunctionId:
3587 break;
3588
3589 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003590 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003591 // C++0x inherited constructors.
3592 if (getLangOptions().CPlusPlus0x) break;
3593
Douglas Gregor220f4272009-11-04 16:30:06 +00003594 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3595 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003596 return 0;
Douglas Gregor220f4272009-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 McCall48871652010-08-21 09:40:31 +00003601 return 0;
Douglas Gregor220f4272009-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 McCall48871652010-08-21 09:40:31 +00003606 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003607 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003608
3609 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3610 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003611 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003612 return 0;
John McCall3969e302009-12-08 07:46:18 +00003613
John McCalla0097262009-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 Gregora771f462010-03-31 17:46:05 +00003622 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003623 }
3624
Douglas Gregorc4356532010-12-16 00:46:58 +00003625 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3626 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3627 return 0;
3628
John McCall3f746822009-11-17 05:59:44 +00003629 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003630 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003631 /* IsInstantiation */ false,
3632 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003633 if (UD)
3634 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003635
John McCall48871652010-08-21 09:40:31 +00003636 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003637}
3638
Douglas Gregor1d9ef842010-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 McCall84d87672009-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 McCalla17e83e2009-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 Gregor1d9ef842010-07-07 23:08:52 +00003727 bool Result;
3728 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3729 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003730
3731 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3732 }
3733
John McCall84d87672009-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 McCalle9cccd82010-06-16 08:42:20 +00003742 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003743 case Ovl_Overload:
3744 return false;
3745
3746 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003747 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003748 break;
3749
3750 // We found a decl with the exact signature.
3751 case Ovl_Match:
John McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003759 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003774 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003783 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCall3f746822009-11-17 05:59:44 +00003789/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003790UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003791 UsingDecl *UD,
3792 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003793
3794 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-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 McCall3f746822009-11-17 05:59:44 +00003799 }
3800
3801 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003802 = UsingShadowDecl::Create(Context, CurContext,
3803 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003804 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003805
3806 Shadow->setAccess(UD->getAccess());
3807 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3808 Shadow->setInvalidDecl();
3809
John McCall3f746822009-11-17 05:59:44 +00003810 if (S)
John McCall3969e302009-12-08 07:46:18 +00003811 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003812 else
John McCall3969e302009-12-08 07:46:18 +00003813 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003814
John McCall3969e302009-12-08 07:46:18 +00003815
John McCall84d87672009-12-10 09:41:52 +00003816 return Shadow;
3817}
John McCall3969e302009-12-08 07:46:18 +00003818
John McCall84d87672009-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 McCallda4458e2010-03-31 01:36:47 +00003847 if (Shadow->getDeclName().getNameKind() ==
3848 DeclarationName::CXXConversionFunctionName)
3849 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3850
John McCall84d87672009-12-10 09:41:52 +00003851 // Remove it from the DeclContext...
3852 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003853
John McCall84d87672009-12-10 09:41:52 +00003854 // ...and the scope, if applicable...
3855 if (S) {
John McCall48871652010-08-21 09:40:31 +00003856 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003857 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003858 }
3859
John McCall84d87672009-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 McCallda4458e2010-03-31 01:36:47 +00003864 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003865}
3866
John McCalle61f2ba2009-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 McCall3f746822009-11-17 05:59:44 +00003872NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3873 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003874 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003875 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003876 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003877 bool IsInstantiation,
3878 bool IsTypeName,
3879 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003880 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003881 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003882 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003883
Anders Carlssonf038fc22009-08-28 05:49:21 +00003884 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003885
Anders Carlsson59140b32009-08-28 03:16:11 +00003886 if (SS.isEmpty()) {
3887 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003888 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003889 }
Mike Stump11289f42009-09-09 15:08:12 +00003890
John McCall84d87672009-12-10 09:41:52 +00003891 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003892 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-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 Stump11289f42009-09-09 15:08:12 +00003912 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003913 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3914
John McCall84d87672009-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 McCallb96ec562009-12-04 22:46:56 +00003920 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3921 return 0;
3922
John McCall84c16cf2009-11-12 03:15:40 +00003923 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003924 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003925 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003926 if (IsTypeName) {
John McCallb96ec562009-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 Bagnara8de74e92010-08-12 11:46:03 +00003931 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003932 } else {
3933 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003934 UsingLoc, SS.getRange(),
3935 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003936 }
John McCallb96ec562009-12-04 22:46:56 +00003937 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003938 D = UsingDecl::Create(Context, CurContext,
3939 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003940 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003941 }
John McCallb96ec562009-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 Stump11289f42009-09-09 15:08:12 +00003947
John McCall0b66eb32010-05-01 00:40:08 +00003948 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003949 UD->setInvalidDecl();
3950 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003951 }
3952
John McCall3969e302009-12-08 07:46:18 +00003953 // Look up the target name.
3954
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003955 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003956
John McCall3969e302009-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 McCalle61f2ba2009-11-18 02:36:19 +00003961 if (!IsInstantiation)
3962 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003963
John McCall27b18f82009-11-17 02:14:36 +00003964 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003965
John McCall9f3059a2009-10-09 21:13:30 +00003966 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003967 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003968 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003969 UD->setInvalidDecl();
3970 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003971 }
3972
John McCallb96ec562009-12-04 22:46:56 +00003973 if (R.isAmbiguous()) {
3974 UD->setInvalidDecl();
3975 return UD;
3976 }
Mike Stump11289f42009-09-09 15:08:12 +00003977
John McCalle61f2ba2009-11-18 02:36:19 +00003978 if (IsTypeName) {
3979 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003980 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-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 McCallb96ec562009-12-04 22:46:56 +00003985 UD->setInvalidDecl();
3986 return UD;
John McCalle61f2ba2009-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 McCallb96ec562009-12-04 22:46:56 +00003992 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-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 McCallb96ec562009-12-04 22:46:56 +00003995 UD->setInvalidDecl();
3996 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003997 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003998 }
3999
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004000 // C++0x N2914 [namespace.udecl]p6:
4001 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004002 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004003 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4004 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004005 UD->setInvalidDecl();
4006 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004007 }
Mike Stump11289f42009-09-09 15:08:12 +00004008
John McCall84d87672009-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 McCall3f746822009-11-17 05:59:44 +00004013
4014 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004015}
4016
John McCall84d87672009-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 Gregor4b718ee2010-05-06 23:31:27 +00004030 //
John McCall032092f2010-11-29 18:01:58 +00004031 // That's in non-member contexts.
4032 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00004068 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004069 return true;
4070 }
4071
4072 return false;
4073}
4074
John McCall3969e302009-12-08 07:46:18 +00004075
John McCallb96ec562009-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 McCall3969e302009-12-08 07:46:18 +00004082 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004083
John McCall3969e302009-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 Gregor7c842292010-12-21 07:41:49 +00004123 if (!NamedContext->isDependentContext() &&
4124 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4125 return true;
4126
John McCall3969e302009-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 McCallb96ec562009-12-04 22:46:56 +00004209}
4210
John McCall48871652010-08-21 09:40:31 +00004211Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004212 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004213 SourceLocation AliasLoc,
4214 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004215 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004216 SourceLocation IdentLoc,
4217 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004218
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004219 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004220 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4221 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004222
Anders Carlssondca83c42009-03-28 06:23:46 +00004223 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-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 Carlssonbb1e4722009-03-28 23:53:49 +00004231 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004232 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004233 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-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 McCall9f3059a2009-10-09 21:13:30 +00004236 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004237 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004238 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004239 }
Mike Stump11289f42009-09-09 15:08:12 +00004240
Anders Carlssondca83c42009-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 McCall48871652010-08-21 09:40:31 +00004245 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004246 }
4247
John McCall27b18f82009-11-17 02:14:36 +00004248 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004249 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004250
John McCall9f3059a2009-10-09 21:13:30 +00004251 if (R.empty()) {
Douglas Gregor9629e9a2010-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 Gregorc048c522010-06-29 19:27:42 +00004269 } else {
4270 R.clear();
4271 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004272 }
4273 }
4274
4275 if (R.empty()) {
4276 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004277 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004278 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004279 }
Mike Stump11289f42009-09-09 15:08:12 +00004280
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004281 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004282 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4283 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004284 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004285 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004286
John McCalld8d0d432010-02-16 06:53:13 +00004287 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004288 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004289}
4290
Douglas Gregora57478e2010-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 Redlc15c3262010-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 Gregor0be31a22010-07-02 17:43:08 +00004337CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4338 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-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 Gregor9672f922010-07-03 00:47:00 +00004345 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4346 "Should not build implicit default constructor!");
4347
Douglas Gregor6d880b12010-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 Gregor9672f922010-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 Redlc15c3262010-09-13 22:02:47 +00004364 else if (CXXConstructorDecl *Constructor
4365 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004366 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004367 }
Douglas Gregor6d880b12010-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 Gregor9672f922010-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 Redlc15c3262010-09-13 22:02:47 +00004379 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004380 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004381 }
Douglas Gregor6d880b12010-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 Gregor9672f922010-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 Redlc15c3262010-09-13 22:02:47 +00004395 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004396 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004397 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004398 }
John McCalldb40c7f2010-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 Gregor6d880b12010-07-01 22:31:05 +00004405
4406 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004407 CanQualType ClassType
4408 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4409 DeclarationName Name
4410 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004411 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004412 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004413 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004414 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004415 0, 0, EPI),
Douglas Gregor4e8b5fb2010-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 Gregor9672f922010-07-03 00:47:00 +00004423
4424 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004425 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4426
Douglas Gregor0be31a22010-07-02 17:43:08 +00004427 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004428 PushOnScopeChains(DefaultCon, S, false);
4429 ClassDecl->addDecl(DefaultCon);
4430
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004431 return DefaultCon;
4432}
4433
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004434void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4435 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004436 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004437 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004438 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004439
Anders Carlsson423f5d82010-04-23 16:04:08 +00004440 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004441 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004442
Douglas Gregora57478e2010-05-01 15:04:51 +00004443 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004444 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004445 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004446 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004447 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004448 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004449 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004450 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004451 }
Douglas Gregor73193272010-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 Jahanian423a81f2009-06-19 19:55:27 +00004458}
4459
Douglas Gregor0be31a22010-07-02 17:43:08 +00004460CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-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 Gregore71edda2010-07-01 22:47:18 +00004480 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-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 Gregore71edda2010-07-01 22:47:18 +00004489 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-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 Gregore71edda2010-07-01 22:47:18 +00004499 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004500 }
4501
Douglas Gregor7454c562010-07-02 20:37:36 +00004502 // Create the actual destructor declaration.
John McCalldb40c7f2010-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 Gregorf1203042010-07-01 19:09:28 +00004509
4510 CanQualType ClassType
4511 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4512 DeclarationName Name
4513 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004514 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004515 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004516 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-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 Gregor7454c562010-07-02 20:37:36 +00004522
4523 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004524 ++ASTContext::NumImplicitDestructorsDeclared;
4525
4526 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004527 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004528 PushOnScopeChains(Destructor, S, false);
4529 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-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 Gregor7454c562010-07-02 20:37:36 +00004535
Douglas Gregorf1203042010-07-01 19:09:28 +00004536 return Destructor;
4537}
4538
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004539void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004540 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004541 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004542 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004543 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004544 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004545
Douglas Gregor54818f02010-05-12 16:39:35 +00004546 if (Destructor->isInvalidDecl())
4547 return;
4548
Douglas Gregora57478e2010-05-01 15:04:51 +00004549 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004550
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004551 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004552 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4553 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004554
Douglas Gregor54818f02010-05-12 16:39:35 +00004555 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-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 Gregor73193272010-09-20 16:48:21 +00004563 SourceLocation Loc = Destructor->getLocation();
4564 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4565
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004566 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004567 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004568}
4569
Douglas Gregorb139cd52010-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 Gregor40c92bb2010-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 Gregorb139cd52010-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 McCalldadc5752010-08-24 06:29:42 +00004594static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004595BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004596 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004597 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-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 McCallab8c2732010-03-16 06:11:48 +00004623 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004624 F.done();
4625
Douglas Gregor40c92bb2010-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 Gregorb139cd52010-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 McCalldadc5752010-08-24 06:29:42 +00004654 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004655 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004656 /*FirstQualifierInScope=*/0, OpLookup,
4657 /*TemplateArgs=*/0,
4658 /*SuppressQualifierCheck=*/true);
4659 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004660 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004661
4662 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004663
John McCalldadc5752010-08-24 06:29:42 +00004664 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004665 OpEqualRef.takeAs<Expr>(),
4666 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004667 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004668 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004669
4670 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004671 }
John McCallab8c2732010-03-16 06:11:48 +00004672
Douglas Gregorb139cd52010-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 McCalle3027922010-08-25 11:45:40 +00004677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004678 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004679 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004680
4681 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004682 }
Douglas Gregorb139cd52010-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 McCall8e7d6562010-08-26 03:08:43 +00004705 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004706
4707 // Initialize the iteration variable to zero.
4708 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004709 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-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 McCall7decc9e2010-11-18 06:31:45 +00004714 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-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 Foad6d4db0c2010-12-07 08:25:34 +00004721 llvm::APInt Upper
4722 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004723 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004724 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-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 Gregorb139cd52010-05-01 20:49:11 +00004728
4729 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004730 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004731 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4732 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004733
4734 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-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 Gregorb139cd52010-05-01 20:49:11 +00004739
4740 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004741 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4742 To, From, CopyingBaseSubobject,
4743 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004744 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004745 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004746
4747 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004748 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004749 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004750 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004751 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004752}
4753
Douglas Gregor330b9cf2010-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 Gregor0be31a22010-07-02 17:43:08 +00004806CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-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 Gregor9672f922010-07-03 00:47:00 +00004811
4812
Douglas Gregorf56ab7b2010-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 Gregor330b9cf2010-07-02 21:50:04 +00004834 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-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 Gregor330b9cf2010-07-02 21:50:04 +00004849 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-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 Gregor68e11362010-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 Gregor330b9cf2010-07-02 21:50:04 +00004870 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004871 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004872
4873 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4874 DeclareImplicitCopyAssignment(BaseClassDecl);
4875
Douglas Gregor68e11362010-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 Gregor330b9cf2010-07-02 21:50:04 +00004886 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004887 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004888
4889 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4890 DeclareImplicitCopyAssignment(FieldClassDecl);
4891
Douglas Gregor68e11362010-07-01 17:48:08 +00004892 if (CXXMethodDecl *CopyAssign
4893 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4894 ExceptSpec.CalledDecl(CopyAssign);
4895 }
4896 }
4897
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004898 // An implicitly-declared copy assignment operator is an inline public
4899 // member of its class.
John McCalldb40c7f2010-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 Gregorf56ab7b2010-07-01 16:36:15 +00004905 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004906 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004907 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004908 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004909 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004910 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004911 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004912 /*isInline=*/true);
4913 CopyAssignment->setAccess(AS_public);
4914 CopyAssignment->setImplicit();
4915 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-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 McCall8e7d6562010-08-26 03:08:43 +00004922 SC_None,
4923 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004924 CopyAssignment->setParams(&FromParam, 1);
4925
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004926 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004927 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4928
Douglas Gregor0be31a22010-07-02 17:43:08 +00004929 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004930 PushOnScopeChains(CopyAssignment, S, false);
4931 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004932
4933 AddOverriddenMethods(ClassDecl, CopyAssignment);
4934 return CopyAssignment;
4935}
4936
Douglas Gregorb139cd52010-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 Gregorebada0772010-06-17 23:14:26 +00004942 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-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 Kyrtzidis18653422010-11-19 00:19:12 +00004955 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-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 McCall37ad5512010-08-23 06:44:23 +00004966 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-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 McCall4bc41ae2010-11-18 19:01:18 +00004983 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-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();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00004998 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004999 Invalid = true;
5000 continue;
5001 }
5002
John McCallcf142162010-08-07 06:22:56 +00005003 CXXCastPath BasePath;
5004 BasePath.push_back(Base);
5005
Douglas Gregorb139cd52010-05-01 20:49:11 +00005006 // Construct the "from" expression, which is an implicit cast to the
5007 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005008 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005009 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005010 CK_UncheckedDerivedToBase,
5011 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005012
5013 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005014 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005015
5016 // Implicitly cast "this" to the appropriately-qualified base type.
5017 Expr *ToE = To.takeAs<Expr>();
5018 ImpCastExprToType(ToE,
5019 Context.getCVRQualifiedType(BaseType,
5020 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005021 CK_UncheckedDerivedToBase,
5022 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005023 To = Owned(ToE);
5024
5025 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005026 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005027 To.get(), From,
5028 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005029 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005030 Diag(CurrentLocation, diag::note_member_synthesized_at)
5031 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5032 CopyAssignOperator->setInvalidDecl();
5033 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005034 }
5035
5036 // Success! Record the copy.
5037 Statements.push_back(Copy.takeAs<Expr>());
5038 }
5039
5040 // \brief Reference to the __builtin_memcpy function.
5041 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005042 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005043 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005044
5045 // Assign non-static members.
5046 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5047 FieldEnd = ClassDecl->field_end();
5048 Field != FieldEnd; ++Field) {
5049 // Check for members of reference type; we can't copy those.
5050 if (Field->getType()->isReferenceType()) {
5051 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5052 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5053 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005054 Diag(CurrentLocation, diag::note_member_synthesized_at)
5055 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005056 Invalid = true;
5057 continue;
5058 }
5059
5060 // Check for members of const-qualified, non-class type.
5061 QualType BaseType = Context.getBaseElementType(Field->getType());
5062 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5063 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5064 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5065 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005066 Diag(CurrentLocation, diag::note_member_synthesized_at)
5067 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005068 Invalid = true;
5069 continue;
5070 }
5071
5072 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005073 if (FieldType->isIncompleteArrayType()) {
5074 assert(ClassDecl->hasFlexibleArrayMember() &&
5075 "Incomplete array type is not valid");
5076 continue;
5077 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005078
5079 // Build references to the field in the object we're copying from and to.
5080 CXXScopeSpec SS; // Intentionally empty
5081 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5082 LookupMemberName);
5083 MemberLookup.addDecl(*Field);
5084 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005085 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005086 Loc, /*IsArrow=*/false,
5087 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005088 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005089 Loc, /*IsArrow=*/true,
5090 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005091 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5092 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5093
5094 // If the field should be copied with __builtin_memcpy rather than via
5095 // explicit assignments, do so. This optimization only applies for arrays
5096 // of scalars and arrays of class type with trivial copy-assignment
5097 // operators.
5098 if (FieldType->isArrayType() &&
5099 (!BaseType->isRecordType() ||
5100 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5101 ->hasTrivialCopyAssignment())) {
5102 // Compute the size of the memory buffer to be copied.
5103 QualType SizeType = Context.getSizeType();
5104 llvm::APInt Size(Context.getTypeSize(SizeType),
5105 Context.getTypeSizeInChars(BaseType).getQuantity());
5106 for (const ConstantArrayType *Array
5107 = Context.getAsConstantArrayType(FieldType);
5108 Array;
5109 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005110 llvm::APInt ArraySize
5111 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005112 Size *= ArraySize;
5113 }
5114
5115 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005116 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5117 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005118
5119 bool NeedsCollectableMemCpy =
5120 (BaseType->isRecordType() &&
5121 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5122
5123 if (NeedsCollectableMemCpy) {
5124 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005125 // Create a reference to the __builtin_objc_memmove_collectable function.
5126 LookupResult R(*this,
5127 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005128 Loc, LookupOrdinaryName);
5129 LookupName(R, TUScope, true);
5130
5131 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5132 if (!CollectableMemCpy) {
5133 // Something went horribly wrong earlier, and we will have
5134 // complained about it.
5135 Invalid = true;
5136 continue;
5137 }
5138
5139 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5140 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005141 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005142 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5143 }
5144 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005145 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005146 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005147 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5148 LookupOrdinaryName);
5149 LookupName(R, TUScope, true);
5150
5151 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5152 if (!BuiltinMemCpy) {
5153 // Something went horribly wrong earlier, and we will have complained
5154 // about it.
5155 Invalid = true;
5156 continue;
5157 }
5158
5159 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5160 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005161 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005162 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5163 }
5164
John McCall37ad5512010-08-23 06:44:23 +00005165 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005166 CallArgs.push_back(To.takeAs<Expr>());
5167 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005168 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005169 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005170 if (NeedsCollectableMemCpy)
5171 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005172 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005173 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005174 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005175 else
5176 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005177 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005178 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005179 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005180
Douglas Gregorb139cd52010-05-01 20:49:11 +00005181 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5182 Statements.push_back(Call.takeAs<Expr>());
5183 continue;
5184 }
5185
5186 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005187 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005188 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005189 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005190 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005191 Diag(CurrentLocation, diag::note_member_synthesized_at)
5192 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5193 CopyAssignOperator->setInvalidDecl();
5194 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005195 }
5196
5197 // Success! Record the copy.
5198 Statements.push_back(Copy.takeAs<Stmt>());
5199 }
5200
5201 if (!Invalid) {
5202 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005203 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005204
John McCalldadc5752010-08-24 06:29:42 +00005205 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005206 if (Return.isInvalid())
5207 Invalid = true;
5208 else {
5209 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005210
5211 if (Trap.hasErrorOccurred()) {
5212 Diag(CurrentLocation, diag::note_member_synthesized_at)
5213 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5214 Invalid = true;
5215 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005216 }
5217 }
5218
5219 if (Invalid) {
5220 CopyAssignOperator->setInvalidDecl();
5221 return;
5222 }
5223
John McCalldadc5752010-08-24 06:29:42 +00005224 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005225 /*isStmtExpr=*/false);
5226 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5227 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005228}
5229
Douglas Gregor0be31a22010-07-02 17:43:08 +00005230CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5231 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005232 // C++ [class.copy]p4:
5233 // If the class definition does not explicitly declare a copy
5234 // constructor, one is declared implicitly.
5235
Douglas Gregor54be3392010-07-01 17:57:27 +00005236 // C++ [class.copy]p5:
5237 // The implicitly-declared copy constructor for a class X will
5238 // have the form
5239 //
5240 // X::X(const X&)
5241 //
5242 // if
5243 bool HasConstCopyConstructor = true;
5244
5245 // -- each direct or virtual base class B of X has a copy
5246 // constructor whose first parameter is of type const B& or
5247 // const volatile B&, and
5248 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5249 BaseEnd = ClassDecl->bases_end();
5250 HasConstCopyConstructor && Base != BaseEnd;
5251 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005252 // Virtual bases are handled below.
5253 if (Base->isVirtual())
5254 continue;
5255
Douglas Gregora6d69502010-07-02 23:41:54 +00005256 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005257 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005258 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5259 DeclareImplicitCopyConstructor(BaseClassDecl);
5260
Douglas Gregorcfe68222010-07-01 18:27:03 +00005261 HasConstCopyConstructor
5262 = BaseClassDecl->hasConstCopyConstructor(Context);
5263 }
5264
5265 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5266 BaseEnd = ClassDecl->vbases_end();
5267 HasConstCopyConstructor && Base != BaseEnd;
5268 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005269 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005270 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005271 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5272 DeclareImplicitCopyConstructor(BaseClassDecl);
5273
Douglas Gregor54be3392010-07-01 17:57:27 +00005274 HasConstCopyConstructor
5275 = BaseClassDecl->hasConstCopyConstructor(Context);
5276 }
5277
5278 // -- for all the nonstatic data members of X that are of a
5279 // class type M (or array thereof), each such class type
5280 // has a copy constructor whose first parameter is of type
5281 // const M& or const volatile M&.
5282 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5283 FieldEnd = ClassDecl->field_end();
5284 HasConstCopyConstructor && Field != FieldEnd;
5285 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005286 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005287 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005288 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005289 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005290 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5291 DeclareImplicitCopyConstructor(FieldClassDecl);
5292
Douglas Gregor54be3392010-07-01 17:57:27 +00005293 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005294 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005295 }
5296 }
5297
5298 // Otherwise, the implicitly declared copy constructor will have
5299 // the form
5300 //
5301 // X::X(X&)
5302 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5303 QualType ArgType = ClassType;
5304 if (HasConstCopyConstructor)
5305 ArgType = ArgType.withConst();
5306 ArgType = Context.getLValueReferenceType(ArgType);
5307
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005308 // C++ [except.spec]p14:
5309 // An implicitly declared special member function (Clause 12) shall have an
5310 // exception-specification. [...]
5311 ImplicitExceptionSpecification ExceptSpec(Context);
5312 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5313 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5314 BaseEnd = ClassDecl->bases_end();
5315 Base != BaseEnd;
5316 ++Base) {
5317 // Virtual bases are handled below.
5318 if (Base->isVirtual())
5319 continue;
5320
Douglas Gregora6d69502010-07-02 23:41:54 +00005321 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005322 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005323 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5324 DeclareImplicitCopyConstructor(BaseClassDecl);
5325
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005326 if (CXXConstructorDecl *CopyConstructor
5327 = BaseClassDecl->getCopyConstructor(Context, Quals))
5328 ExceptSpec.CalledDecl(CopyConstructor);
5329 }
5330 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5331 BaseEnd = ClassDecl->vbases_end();
5332 Base != BaseEnd;
5333 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005334 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005335 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005336 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5337 DeclareImplicitCopyConstructor(BaseClassDecl);
5338
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005339 if (CXXConstructorDecl *CopyConstructor
5340 = BaseClassDecl->getCopyConstructor(Context, Quals))
5341 ExceptSpec.CalledDecl(CopyConstructor);
5342 }
5343 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5344 FieldEnd = ClassDecl->field_end();
5345 Field != FieldEnd;
5346 ++Field) {
5347 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5348 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005349 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005350 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005351 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5352 DeclareImplicitCopyConstructor(FieldClassDecl);
5353
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005354 if (CXXConstructorDecl *CopyConstructor
5355 = FieldClassDecl->getCopyConstructor(Context, Quals))
5356 ExceptSpec.CalledDecl(CopyConstructor);
5357 }
5358 }
5359
Douglas Gregor54be3392010-07-01 17:57:27 +00005360 // An implicitly-declared copy constructor is an inline public
5361 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005362 FunctionProtoType::ExtProtoInfo EPI;
5363 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5364 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5365 EPI.NumExceptions = ExceptSpec.size();
5366 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005367 DeclarationName Name
5368 = Context.DeclarationNames.getCXXConstructorName(
5369 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005370 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005371 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005372 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005373 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005374 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005375 /*TInfo=*/0,
5376 /*isExplicit=*/false,
5377 /*isInline=*/true,
5378 /*isImplicitlyDeclared=*/true);
5379 CopyConstructor->setAccess(AS_public);
5380 CopyConstructor->setImplicit();
5381 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5382
Douglas Gregora6d69502010-07-02 23:41:54 +00005383 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005384 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5385
Douglas Gregor54be3392010-07-01 17:57:27 +00005386 // Add the parameter to the constructor.
5387 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5388 ClassDecl->getLocation(),
5389 /*IdentifierInfo=*/0,
5390 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005391 SC_None,
5392 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005393 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005394 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005395 PushOnScopeChains(CopyConstructor, S, false);
5396 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005397
5398 return CopyConstructor;
5399}
5400
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005401void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5402 CXXConstructorDecl *CopyConstructor,
5403 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005404 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005405 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005406 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005407 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005408
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005409 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005410 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005411
Douglas Gregora57478e2010-05-01 15:04:51 +00005412 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005413 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005414
Alexis Hunt1d792652011-01-08 20:30:50 +00005415 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005416 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005417 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005418 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005419 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005420 } else {
5421 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5422 CopyConstructor->getLocation(),
5423 MultiStmtArg(*this, 0, 0),
5424 /*isStmtExpr=*/false)
5425 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005426 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005427
5428 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005429}
5430
John McCalldadc5752010-08-24 06:29:42 +00005431ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005432Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005433 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005434 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005435 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005436 unsigned ConstructKind,
5437 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005438 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005439
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005440 // C++0x [class.copy]p34:
5441 // When certain criteria are met, an implementation is allowed to
5442 // omit the copy/move construction of a class object, even if the
5443 // copy/move constructor and/or destructor for the object have
5444 // side effects. [...]
5445 // - when a temporary class object that has not been bound to a
5446 // reference (12.2) would be copied/moved to a class object
5447 // with the same cv-unqualified type, the copy/move operation
5448 // can be omitted by constructing the temporary object
5449 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005450 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5451 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005452 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005453 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005454 }
Mike Stump11289f42009-09-09 15:08:12 +00005455
5456 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005457 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005458 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005459}
5460
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005461/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5462/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005463ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005464Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5465 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005466 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005467 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005468 unsigned ConstructKind,
5469 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005470 unsigned NumExprs = ExprArgs.size();
5471 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005472
Douglas Gregor27381f32009-11-23 12:27:39 +00005473 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005474 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005475 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005476 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005477 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5478 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005479}
5480
Mike Stump11289f42009-09-09 15:08:12 +00005481bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005482 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005483 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005484 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005485 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005486 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005487 move(Exprs), false, CXXConstructExpr::CK_Complete,
5488 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005489 if (TempResult.isInvalid())
5490 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005491
Anders Carlsson6eb55572009-08-25 05:12:04 +00005492 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005493 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005494 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005495 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005496 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005497
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005498 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005499}
5500
John McCall03c48482010-02-02 09:10:11 +00005501void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5502 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005503 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005504 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005505 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005506 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005507 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005508 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005509 << VD->getDeclName()
5510 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005511
John McCall386dfc72010-09-18 05:25:11 +00005512 // TODO: this should be re-enabled for static locals by !CXAAtExit
5513 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005514 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005515 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005516}
5517
Mike Stump11289f42009-09-09 15:08:12 +00005518/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005519/// ActOnDeclarator, when a C++ direct initializer is present.
5520/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005521void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005522 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005523 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005524 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005525 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005526
5527 // If there is no declaration, there was an error parsing it. Just ignore
5528 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005529 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005530 return;
Mike Stump11289f42009-09-09 15:08:12 +00005531
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005532 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5533 if (!VDecl) {
5534 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5535 RealDecl->setInvalidDecl();
5536 return;
5537 }
5538
Douglas Gregor402250f2009-08-26 21:14:46 +00005539 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005540 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005541 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5542 //
5543 // Clients that want to distinguish between the two forms, can check for
5544 // direct initializer using VarDecl::hasCXXDirectInitializer().
5545 // A major benefit is that clients that don't particularly care about which
5546 // exactly form was it (like the CodeGen) can handle both cases without
5547 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005548
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005549 // C++ 8.5p11:
5550 // The form of initialization (using parentheses or '=') is generally
5551 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005552 // class type.
5553
Douglas Gregor50dc2192010-02-11 22:55:30 +00005554 if (!VDecl->getType()->isDependentType() &&
5555 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005556 diag::err_typecheck_decl_incomplete_type)) {
5557 VDecl->setInvalidDecl();
5558 return;
5559 }
5560
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005561 // The variable can not have an abstract class type.
5562 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5563 diag::err_abstract_type_in_decl,
5564 AbstractVariableType))
5565 VDecl->setInvalidDecl();
5566
Sebastian Redl5ca79842010-02-01 20:16:42 +00005567 const VarDecl *Def;
5568 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005569 Diag(VDecl->getLocation(), diag::err_redefinition)
5570 << VDecl->getDeclName();
5571 Diag(Def->getLocation(), diag::note_previous_definition);
5572 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005573 return;
5574 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005575
Douglas Gregorf0f83692010-08-24 05:27:49 +00005576 // C++ [class.static.data]p4
5577 // If a static data member is of const integral or const
5578 // enumeration type, its declaration in the class definition can
5579 // specify a constant-initializer which shall be an integral
5580 // constant expression (5.19). In that case, the member can appear
5581 // in integral constant expressions. The member shall still be
5582 // defined in a namespace scope if it is used in the program and the
5583 // namespace scope definition shall not contain an initializer.
5584 //
5585 // We already performed a redefinition check above, but for static
5586 // data members we also need to check whether there was an in-class
5587 // declaration with an initializer.
5588 const VarDecl* PrevInit = 0;
5589 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5590 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5591 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5592 return;
5593 }
5594
Douglas Gregor71f39c92010-12-16 01:31:22 +00005595 bool IsDependent = false;
5596 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5597 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5598 VDecl->setInvalidDecl();
5599 return;
5600 }
5601
5602 if (Exprs.get()[I]->isTypeDependent())
5603 IsDependent = true;
5604 }
5605
Douglas Gregor50dc2192010-02-11 22:55:30 +00005606 // If either the declaration has a dependent type or if any of the
5607 // expressions is type-dependent, we represent the initialization
5608 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005609 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005610 // Let clients know that initialization was done with a direct initializer.
5611 VDecl->setCXXDirectInitializer(true);
5612
5613 // Store the initialization expressions as a ParenListExpr.
5614 unsigned NumExprs = Exprs.size();
5615 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5616 (Expr **)Exprs.release(),
5617 NumExprs, RParenLoc));
5618 return;
5619 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005620
5621 // Capture the variable that is being initialized and the style of
5622 // initialization.
5623 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5624
5625 // FIXME: Poor source location information.
5626 InitializationKind Kind
5627 = InitializationKind::CreateDirect(VDecl->getLocation(),
5628 LParenLoc, RParenLoc);
5629
5630 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005631 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005632 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005633 if (Result.isInvalid()) {
5634 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005635 return;
5636 }
John McCallacf0ee52010-10-08 02:01:28 +00005637
5638 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005639
Douglas Gregora40433a2010-12-07 00:41:46 +00005640 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005641 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005642 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005643
John McCall8b7fd8f12011-01-19 11:48:09 +00005644 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005645}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005646
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005647/// \brief Given a constructor and the set of arguments provided for the
5648/// constructor, convert the arguments and add any required default arguments
5649/// to form a proper call to this constructor.
5650///
5651/// \returns true if an error occurred, false otherwise.
5652bool
5653Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5654 MultiExprArg ArgsPtr,
5655 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005656 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005657 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5658 unsigned NumArgs = ArgsPtr.size();
5659 Expr **Args = (Expr **)ArgsPtr.get();
5660
5661 const FunctionProtoType *Proto
5662 = Constructor->getType()->getAs<FunctionProtoType>();
5663 assert(Proto && "Constructor without a prototype?");
5664 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005665
5666 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005667 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005668 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005669 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005670 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005671
5672 VariadicCallType CallType =
5673 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5674 llvm::SmallVector<Expr *, 8> AllArgs;
5675 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5676 Proto, 0, Args, NumArgs, AllArgs,
5677 CallType);
5678 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5679 ConvertedArgs.push_back(AllArgs[i]);
5680 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005681}
5682
Anders Carlssone363c8e2009-12-12 00:32:00 +00005683static inline bool
5684CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5685 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005686 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005687 if (isa<NamespaceDecl>(DC)) {
5688 return SemaRef.Diag(FnDecl->getLocation(),
5689 diag::err_operator_new_delete_declared_in_namespace)
5690 << FnDecl->getDeclName();
5691 }
5692
5693 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005694 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005695 return SemaRef.Diag(FnDecl->getLocation(),
5696 diag::err_operator_new_delete_declared_static)
5697 << FnDecl->getDeclName();
5698 }
5699
Anders Carlsson60659a82009-12-12 02:43:16 +00005700 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005701}
5702
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005703static inline bool
5704CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5705 CanQualType ExpectedResultType,
5706 CanQualType ExpectedFirstParamType,
5707 unsigned DependentParamTypeDiag,
5708 unsigned InvalidParamTypeDiag) {
5709 QualType ResultType =
5710 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5711
5712 // Check that the result type is not dependent.
5713 if (ResultType->isDependentType())
5714 return SemaRef.Diag(FnDecl->getLocation(),
5715 diag::err_operator_new_delete_dependent_result_type)
5716 << FnDecl->getDeclName() << ExpectedResultType;
5717
5718 // Check that the result type is what we expect.
5719 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5720 return SemaRef.Diag(FnDecl->getLocation(),
5721 diag::err_operator_new_delete_invalid_result_type)
5722 << FnDecl->getDeclName() << ExpectedResultType;
5723
5724 // A function template must have at least 2 parameters.
5725 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5726 return SemaRef.Diag(FnDecl->getLocation(),
5727 diag::err_operator_new_delete_template_too_few_parameters)
5728 << FnDecl->getDeclName();
5729
5730 // The function decl must have at least 1 parameter.
5731 if (FnDecl->getNumParams() == 0)
5732 return SemaRef.Diag(FnDecl->getLocation(),
5733 diag::err_operator_new_delete_too_few_parameters)
5734 << FnDecl->getDeclName();
5735
5736 // Check the the first parameter type is not dependent.
5737 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5738 if (FirstParamType->isDependentType())
5739 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5740 << FnDecl->getDeclName() << ExpectedFirstParamType;
5741
5742 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005743 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005744 ExpectedFirstParamType)
5745 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5746 << FnDecl->getDeclName() << ExpectedFirstParamType;
5747
5748 return false;
5749}
5750
Anders Carlsson12308f42009-12-11 23:23:22 +00005751static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005752CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005753 // C++ [basic.stc.dynamic.allocation]p1:
5754 // A program is ill-formed if an allocation function is declared in a
5755 // namespace scope other than global scope or declared static in global
5756 // scope.
5757 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5758 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005759
5760 CanQualType SizeTy =
5761 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5762
5763 // C++ [basic.stc.dynamic.allocation]p1:
5764 // The return type shall be void*. The first parameter shall have type
5765 // std::size_t.
5766 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5767 SizeTy,
5768 diag::err_operator_new_dependent_param_type,
5769 diag::err_operator_new_param_type))
5770 return true;
5771
5772 // C++ [basic.stc.dynamic.allocation]p1:
5773 // The first parameter shall not have an associated default argument.
5774 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005775 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005776 diag::err_operator_new_default_arg)
5777 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5778
5779 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005780}
5781
5782static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005783CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5784 // C++ [basic.stc.dynamic.deallocation]p1:
5785 // A program is ill-formed if deallocation functions are declared in a
5786 // namespace scope other than global scope or declared static in global
5787 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005788 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5789 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005790
5791 // C++ [basic.stc.dynamic.deallocation]p2:
5792 // Each deallocation function shall return void and its first parameter
5793 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005794 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5795 SemaRef.Context.VoidPtrTy,
5796 diag::err_operator_delete_dependent_param_type,
5797 diag::err_operator_delete_param_type))
5798 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005799
Anders Carlsson12308f42009-12-11 23:23:22 +00005800 return false;
5801}
5802
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005803/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5804/// of this overloaded operator is well-formed. If so, returns false;
5805/// otherwise, emits appropriate diagnostics and returns true.
5806bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005807 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005808 "Expected an overloaded operator declaration");
5809
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005810 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5811
Mike Stump11289f42009-09-09 15:08:12 +00005812 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005813 // The allocation and deallocation functions, operator new,
5814 // operator new[], operator delete and operator delete[], are
5815 // described completely in 3.7.3. The attributes and restrictions
5816 // found in the rest of this subclause do not apply to them unless
5817 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005818 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005819 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005820
Anders Carlsson22f443f2009-12-12 00:26:23 +00005821 if (Op == OO_New || Op == OO_Array_New)
5822 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005823
5824 // C++ [over.oper]p6:
5825 // An operator function shall either be a non-static member
5826 // function or be a non-member function and have at least one
5827 // parameter whose type is a class, a reference to a class, an
5828 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005829 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5830 if (MethodDecl->isStatic())
5831 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005832 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005833 } else {
5834 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005835 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5836 ParamEnd = FnDecl->param_end();
5837 Param != ParamEnd; ++Param) {
5838 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005839 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5840 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005841 ClassOrEnumParam = true;
5842 break;
5843 }
5844 }
5845
Douglas Gregord69246b2008-11-17 16:14:12 +00005846 if (!ClassOrEnumParam)
5847 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005848 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005849 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005850 }
5851
5852 // C++ [over.oper]p8:
5853 // An operator function cannot have default arguments (8.3.6),
5854 // except where explicitly stated below.
5855 //
Mike Stump11289f42009-09-09 15:08:12 +00005856 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005857 // (C++ [over.call]p1).
5858 if (Op != OO_Call) {
5859 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5860 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005861 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005862 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005863 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005864 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005865 }
5866 }
5867
Douglas Gregor6cf08062008-11-10 13:38:07 +00005868 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5869 { false, false, false }
5870#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5871 , { Unary, Binary, MemberOnly }
5872#include "clang/Basic/OperatorKinds.def"
5873 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005874
Douglas Gregor6cf08062008-11-10 13:38:07 +00005875 bool CanBeUnaryOperator = OperatorUses[Op][0];
5876 bool CanBeBinaryOperator = OperatorUses[Op][1];
5877 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005878
5879 // C++ [over.oper]p8:
5880 // [...] Operator functions cannot have more or fewer parameters
5881 // than the number required for the corresponding operator, as
5882 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005883 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005884 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005885 if (Op != OO_Call &&
5886 ((NumParams == 1 && !CanBeUnaryOperator) ||
5887 (NumParams == 2 && !CanBeBinaryOperator) ||
5888 (NumParams < 1) || (NumParams > 2))) {
5889 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005890 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005891 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005892 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005893 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005894 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005895 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005896 assert(CanBeBinaryOperator &&
5897 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005898 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005899 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005900
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005901 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005902 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005903 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005904
Douglas Gregord69246b2008-11-17 16:14:12 +00005905 // Overloaded operators other than operator() cannot be variadic.
5906 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005907 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005908 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005909 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005910 }
5911
5912 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005913 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5914 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005915 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005916 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005917 }
5918
5919 // C++ [over.inc]p1:
5920 // The user-defined function called operator++ implements the
5921 // prefix and postfix ++ operator. If this function is a member
5922 // function with no parameters, or a non-member function with one
5923 // parameter of class or enumeration type, it defines the prefix
5924 // increment operator ++ for objects of that type. If the function
5925 // is a member function with one parameter (which shall be of type
5926 // int) or a non-member function with two parameters (the second
5927 // of which shall be of type int), it defines the postfix
5928 // increment operator ++ for objects of that type.
5929 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5930 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5931 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005932 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005933 ParamIsInt = BT->getKind() == BuiltinType::Int;
5934
Chris Lattner2b786902008-11-21 07:50:02 +00005935 if (!ParamIsInt)
5936 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005937 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005938 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005939 }
5940
Douglas Gregord69246b2008-11-17 16:14:12 +00005941 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005942}
Chris Lattner3b024a32008-12-17 07:09:26 +00005943
Alexis Huntc88db062010-01-13 09:01:02 +00005944/// CheckLiteralOperatorDeclaration - Check whether the declaration
5945/// of this literal operator function is well-formed. If so, returns
5946/// false; otherwise, emits appropriate diagnostics and returns true.
5947bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5948 DeclContext *DC = FnDecl->getDeclContext();
5949 Decl::Kind Kind = DC->getDeclKind();
5950 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5951 Kind != Decl::LinkageSpec) {
5952 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5953 << FnDecl->getDeclName();
5954 return true;
5955 }
5956
5957 bool Valid = false;
5958
Alexis Hunt7dd26172010-04-07 23:11:06 +00005959 // template <char...> type operator "" name() is the only valid template
5960 // signature, and the only valid signature with no parameters.
5961 if (FnDecl->param_size() == 0) {
5962 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5963 // Must have only one template parameter
5964 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5965 if (Params->size() == 1) {
5966 NonTypeTemplateParmDecl *PmDecl =
5967 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005968
Alexis Hunt7dd26172010-04-07 23:11:06 +00005969 // The template parameter must be a char parameter pack.
5970 // FIXME: This test will always fail because non-type parameter packs
5971 // have not been implemented.
5972 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5973 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5974 Valid = true;
5975 }
5976 }
5977 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005978 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005979 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5980
Alexis Huntc88db062010-01-13 09:01:02 +00005981 QualType T = (*Param)->getType();
5982
Alexis Hunt079a6f72010-04-07 22:57:35 +00005983 // unsigned long long int, long double, and any character type are allowed
5984 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005985 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5986 Context.hasSameType(T, Context.LongDoubleTy) ||
5987 Context.hasSameType(T, Context.CharTy) ||
5988 Context.hasSameType(T, Context.WCharTy) ||
5989 Context.hasSameType(T, Context.Char16Ty) ||
5990 Context.hasSameType(T, Context.Char32Ty)) {
5991 if (++Param == FnDecl->param_end())
5992 Valid = true;
5993 goto FinishedParams;
5994 }
5995
Alexis Hunt079a6f72010-04-07 22:57:35 +00005996 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005997 const PointerType *PT = T->getAs<PointerType>();
5998 if (!PT)
5999 goto FinishedParams;
6000 T = PT->getPointeeType();
6001 if (!T.isConstQualified())
6002 goto FinishedParams;
6003 T = T.getUnqualifiedType();
6004
6005 // Move on to the second parameter;
6006 ++Param;
6007
6008 // If there is no second parameter, the first must be a const char *
6009 if (Param == FnDecl->param_end()) {
6010 if (Context.hasSameType(T, Context.CharTy))
6011 Valid = true;
6012 goto FinishedParams;
6013 }
6014
6015 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6016 // are allowed as the first parameter to a two-parameter function
6017 if (!(Context.hasSameType(T, Context.CharTy) ||
6018 Context.hasSameType(T, Context.WCharTy) ||
6019 Context.hasSameType(T, Context.Char16Ty) ||
6020 Context.hasSameType(T, Context.Char32Ty)))
6021 goto FinishedParams;
6022
6023 // The second and final parameter must be an std::size_t
6024 T = (*Param)->getType().getUnqualifiedType();
6025 if (Context.hasSameType(T, Context.getSizeType()) &&
6026 ++Param == FnDecl->param_end())
6027 Valid = true;
6028 }
6029
6030 // FIXME: This diagnostic is absolutely terrible.
6031FinishedParams:
6032 if (!Valid) {
6033 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6034 << FnDecl->getDeclName();
6035 return true;
6036 }
6037
6038 return false;
6039}
6040
Douglas Gregor07665a62009-01-05 19:45:36 +00006041/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6042/// linkage specification, including the language and (if present)
6043/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6044/// the location of the language string literal, which is provided
6045/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6046/// the '{' brace. Otherwise, this linkage specification does not
6047/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006048Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6049 SourceLocation LangLoc,
6050 llvm::StringRef Lang,
6051 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006052 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006053 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006054 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006055 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006056 Language = LinkageSpecDecl::lang_cxx;
6057 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006058 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006059 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006060 }
Mike Stump11289f42009-09-09 15:08:12 +00006061
Chris Lattner438e5012008-12-17 07:13:27 +00006062 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006063
Douglas Gregor07665a62009-01-05 19:45:36 +00006064 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006065 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006066 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006067 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006068 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006069 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006070}
6071
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006072/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006073/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6074/// valid, it's the position of the closing '}' brace in a linkage
6075/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006076Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6077 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006078 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006079 if (LinkageSpec)
6080 PopDeclContext();
6081 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006082}
6083
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006084/// \brief Perform semantic analysis for the variable declaration that
6085/// occurs within a C++ catch clause, returning the newly-created
6086/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006087VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006088 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006089 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006090 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006091 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006092 QualType ExDeclType = TInfo->getType();
6093
Sebastian Redl54c04d42008-12-22 19:15:10 +00006094 // Arrays and functions decay.
6095 if (ExDeclType->isArrayType())
6096 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6097 else if (ExDeclType->isFunctionType())
6098 ExDeclType = Context.getPointerType(ExDeclType);
6099
6100 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6101 // The exception-declaration shall not denote a pointer or reference to an
6102 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006103 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006104 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006105 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006106 Invalid = true;
6107 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006108
Douglas Gregor104ee002010-03-08 01:47:36 +00006109 // GCC allows catching pointers and references to incomplete types
6110 // as an extension; so do we, but we warn by default.
6111
Sebastian Redl54c04d42008-12-22 19:15:10 +00006112 QualType BaseType = ExDeclType;
6113 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006114 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006115 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006116 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006117 BaseType = Ptr->getPointeeType();
6118 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006119 DK = diag::ext_catch_incomplete_ptr;
6120 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006121 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006122 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006123 BaseType = Ref->getPointeeType();
6124 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006125 DK = diag::ext_catch_incomplete_ref;
6126 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006127 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006128 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006129 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6130 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006131 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006132
Mike Stump11289f42009-09-09 15:08:12 +00006133 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006134 RequireNonAbstractType(Loc, ExDeclType,
6135 diag::err_abstract_type_in_decl,
6136 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006137 Invalid = true;
6138
John McCall2ca705e2010-07-24 00:37:23 +00006139 // Only the non-fragile NeXT runtime currently supports C++ catches
6140 // of ObjC types, and no runtime supports catching ObjC types by value.
6141 if (!Invalid && getLangOptions().ObjC1) {
6142 QualType T = ExDeclType;
6143 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6144 T = RT->getPointeeType();
6145
6146 if (T->isObjCObjectType()) {
6147 Diag(Loc, diag::err_objc_object_catch);
6148 Invalid = true;
6149 } else if (T->isObjCObjectPointerType()) {
6150 if (!getLangOptions().NeXTRuntime) {
6151 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6152 Invalid = true;
6153 } else if (!getLangOptions().ObjCNonFragileABI) {
6154 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6155 Invalid = true;
6156 }
6157 }
6158 }
6159
Mike Stump11289f42009-09-09 15:08:12 +00006160 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006161 Name, ExDeclType, TInfo, SC_None,
6162 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006163 ExDecl->setExceptionVariable(true);
6164
Douglas Gregor6de584c2010-03-05 23:38:39 +00006165 if (!Invalid) {
6166 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6167 // C++ [except.handle]p16:
6168 // The object declared in an exception-declaration or, if the
6169 // exception-declaration does not specify a name, a temporary (12.2) is
6170 // copy-initialized (8.5) from the exception object. [...]
6171 // The object is destroyed when the handler exits, after the destruction
6172 // of any automatic objects initialized within the handler.
6173 //
6174 // We just pretend to initialize the object with itself, then make sure
6175 // it can be destroyed later.
6176 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6177 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006178 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006179 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6180 SourceLocation());
6181 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006182 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006183 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006184 if (Result.isInvalid())
6185 Invalid = true;
6186 else
6187 FinalizeVarWithDestructor(ExDecl, RecordTy);
6188 }
6189 }
6190
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006191 if (Invalid)
6192 ExDecl->setInvalidDecl();
6193
6194 return ExDecl;
6195}
6196
6197/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6198/// handler.
John McCall48871652010-08-21 09:40:31 +00006199Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006200 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006201 bool Invalid = D.isInvalidType();
6202
6203 // Check for unexpanded parameter packs.
6204 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6205 UPPC_ExceptionType)) {
6206 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6207 D.getIdentifierLoc());
6208 Invalid = true;
6209 }
6210
Sebastian Redl54c04d42008-12-22 19:15:10 +00006211 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006212 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006213 LookupOrdinaryName,
6214 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006215 // The scope should be freshly made just for us. There is just no way
6216 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006217 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006218 if (PrevDecl->isTemplateParameter()) {
6219 // Maybe we will complain about the shadowed template parameter.
6220 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006221 }
6222 }
6223
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006224 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006225 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6226 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006227 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006228 }
6229
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006230 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006231 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006232 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006233
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006234 if (Invalid)
6235 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006236
Sebastian Redl54c04d42008-12-22 19:15:10 +00006237 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006238 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006239 PushOnScopeChains(ExDecl, S);
6240 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006241 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006242
Douglas Gregor758a8692009-06-17 21:51:59 +00006243 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006244 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006245}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006246
John McCall48871652010-08-21 09:40:31 +00006247Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006248 Expr *AssertExpr,
6249 Expr *AssertMessageExpr_) {
6250 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006251
Anders Carlsson54b26982009-03-14 00:33:21 +00006252 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6253 llvm::APSInt Value(32);
6254 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6255 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6256 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006257 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006258 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006259
Anders Carlsson54b26982009-03-14 00:33:21 +00006260 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006261 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006262 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006263 }
6264 }
Mike Stump11289f42009-09-09 15:08:12 +00006265
Douglas Gregoref68fee2010-12-15 23:55:21 +00006266 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6267 return 0;
6268
Mike Stump11289f42009-09-09 15:08:12 +00006269 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006270 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006271
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006272 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006273 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006274}
Sebastian Redlf769df52009-03-24 22:27:57 +00006275
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006276/// \brief Perform semantic analysis of the given friend type declaration.
6277///
6278/// \returns A friend declaration that.
6279FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6280 TypeSourceInfo *TSInfo) {
6281 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6282
6283 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006284 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006285
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006286 if (!getLangOptions().CPlusPlus0x) {
6287 // C++03 [class.friend]p2:
6288 // An elaborated-type-specifier shall be used in a friend declaration
6289 // for a class.*
6290 //
6291 // * The class-key of the elaborated-type-specifier is required.
6292 if (!ActiveTemplateInstantiations.empty()) {
6293 // Do not complain about the form of friend template types during
6294 // template instantiation; we will already have complained when the
6295 // template was declared.
6296 } else if (!T->isElaboratedTypeSpecifier()) {
6297 // If we evaluated the type to a record type, suggest putting
6298 // a tag in front.
6299 if (const RecordType *RT = T->getAs<RecordType>()) {
6300 RecordDecl *RD = RT->getDecl();
6301
6302 std::string InsertionText = std::string(" ") + RD->getKindName();
6303
6304 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6305 << (unsigned) RD->getTagKind()
6306 << T
6307 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6308 InsertionText);
6309 } else {
6310 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6311 << T
6312 << SourceRange(FriendLoc, TypeRange.getEnd());
6313 }
6314 } else if (T->getAs<EnumType>()) {
6315 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006316 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006317 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006318 }
6319 }
6320
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006321 // C++0x [class.friend]p3:
6322 // If the type specifier in a friend declaration designates a (possibly
6323 // cv-qualified) class type, that class is declared as a friend; otherwise,
6324 // the friend declaration is ignored.
6325
6326 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6327 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006328
6329 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6330}
6331
John McCallace48cd2010-10-19 01:40:49 +00006332/// Handle a friend tag declaration where the scope specifier was
6333/// templated.
6334Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6335 unsigned TagSpec, SourceLocation TagLoc,
6336 CXXScopeSpec &SS,
6337 IdentifierInfo *Name, SourceLocation NameLoc,
6338 AttributeList *Attr,
6339 MultiTemplateParamsArg TempParamLists) {
6340 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6341
6342 bool isExplicitSpecialization = false;
6343 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6344 bool Invalid = false;
6345
6346 if (TemplateParameterList *TemplateParams
6347 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6348 TempParamLists.get(),
6349 TempParamLists.size(),
6350 /*friend*/ true,
6351 isExplicitSpecialization,
6352 Invalid)) {
6353 --NumMatchedTemplateParamLists;
6354
6355 if (TemplateParams->size() > 0) {
6356 // This is a declaration of a class template.
6357 if (Invalid)
6358 return 0;
6359
6360 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6361 SS, Name, NameLoc, Attr,
6362 TemplateParams, AS_public).take();
6363 } else {
6364 // The "template<>" header is extraneous.
6365 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6366 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6367 isExplicitSpecialization = true;
6368 }
6369 }
6370
6371 if (Invalid) return 0;
6372
6373 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6374
6375 bool isAllExplicitSpecializations = true;
6376 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6377 if (TempParamLists.get()[I]->size()) {
6378 isAllExplicitSpecializations = false;
6379 break;
6380 }
6381 }
6382
6383 // FIXME: don't ignore attributes.
6384
6385 // If it's explicit specializations all the way down, just forget
6386 // about the template header and build an appropriate non-templated
6387 // friend. TODO: for source fidelity, remember the headers.
6388 if (isAllExplicitSpecializations) {
6389 ElaboratedTypeKeyword Keyword
6390 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6391 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6392 TagLoc, SS.getRange(), NameLoc);
6393 if (T.isNull())
6394 return 0;
6395
6396 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6397 if (isa<DependentNameType>(T)) {
6398 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6399 TL.setKeywordLoc(TagLoc);
6400 TL.setQualifierRange(SS.getRange());
6401 TL.setNameLoc(NameLoc);
6402 } else {
6403 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6404 TL.setKeywordLoc(TagLoc);
6405 TL.setQualifierRange(SS.getRange());
6406 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6407 }
6408
6409 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6410 TSI, FriendLoc);
6411 Friend->setAccess(AS_public);
6412 CurContext->addDecl(Friend);
6413 return Friend;
6414 }
6415
6416 // Handle the case of a templated-scope friend class. e.g.
6417 // template <class T> class A<T>::B;
6418 // FIXME: we don't support these right now.
6419 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6420 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6421 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6422 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6423 TL.setKeywordLoc(TagLoc);
6424 TL.setQualifierRange(SS.getRange());
6425 TL.setNameLoc(NameLoc);
6426
6427 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6428 TSI, FriendLoc);
6429 Friend->setAccess(AS_public);
6430 Friend->setUnsupportedFriend(true);
6431 CurContext->addDecl(Friend);
6432 return Friend;
6433}
6434
6435
John McCall11083da2009-09-16 22:47:08 +00006436/// Handle a friend type declaration. This works in tandem with
6437/// ActOnTag.
6438///
6439/// Notes on friend class templates:
6440///
6441/// We generally treat friend class declarations as if they were
6442/// declaring a class. So, for example, the elaborated type specifier
6443/// in a friend declaration is required to obey the restrictions of a
6444/// class-head (i.e. no typedefs in the scope chain), template
6445/// parameters are required to match up with simple template-ids, &c.
6446/// However, unlike when declaring a template specialization, it's
6447/// okay to refer to a template specialization without an empty
6448/// template parameter declaration, e.g.
6449/// friend class A<T>::B<unsigned>;
6450/// We permit this as a special case; if there are any template
6451/// parameters present at all, require proper matching, i.e.
6452/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006453Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006454 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006455 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006456
6457 assert(DS.isFriendSpecified());
6458 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6459
John McCall11083da2009-09-16 22:47:08 +00006460 // Try to convert the decl specifier to a type. This works for
6461 // friend templates because ActOnTag never produces a ClassTemplateDecl
6462 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006463 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006464 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6465 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006466 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006467 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006468
Douglas Gregor6c110f32010-12-16 01:14:37 +00006469 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6470 return 0;
6471
John McCall11083da2009-09-16 22:47:08 +00006472 // This is definitely an error in C++98. It's probably meant to
6473 // be forbidden in C++0x, too, but the specification is just
6474 // poorly written.
6475 //
6476 // The problem is with declarations like the following:
6477 // template <T> friend A<T>::foo;
6478 // where deciding whether a class C is a friend or not now hinges
6479 // on whether there exists an instantiation of A that causes
6480 // 'foo' to equal C. There are restrictions on class-heads
6481 // (which we declare (by fiat) elaborated friend declarations to
6482 // be) that makes this tractable.
6483 //
6484 // FIXME: handle "template <> friend class A<T>;", which
6485 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006486 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006487 Diag(Loc, diag::err_tagless_friend_type_template)
6488 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006489 return 0;
John McCall11083da2009-09-16 22:47:08 +00006490 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006491
John McCallaa74a0c2009-08-28 07:59:38 +00006492 // C++98 [class.friend]p1: A friend of a class is a function
6493 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006494 // This is fixed in DR77, which just barely didn't make the C++03
6495 // deadline. It's also a very silly restriction that seriously
6496 // affects inner classes and which nobody else seems to implement;
6497 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006498 //
6499 // But note that we could warn about it: it's always useless to
6500 // friend one of your own members (it's not, however, worthless to
6501 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006502
John McCall11083da2009-09-16 22:47:08 +00006503 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006504 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006505 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006506 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006507 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006508 TSI,
John McCall11083da2009-09-16 22:47:08 +00006509 DS.getFriendSpecLoc());
6510 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006511 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6512
6513 if (!D)
John McCall48871652010-08-21 09:40:31 +00006514 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006515
John McCall11083da2009-09-16 22:47:08 +00006516 D->setAccess(AS_public);
6517 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006518
John McCall48871652010-08-21 09:40:31 +00006519 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006520}
6521
John McCallde3fd222010-10-12 23:13:28 +00006522Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6523 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006524 const DeclSpec &DS = D.getDeclSpec();
6525
6526 assert(DS.isFriendSpecified());
6527 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6528
6529 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006530 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6531 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006532
6533 // C++ [class.friend]p1
6534 // A friend of a class is a function or class....
6535 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006536 // It *doesn't* see through dependent types, which is correct
6537 // according to [temp.arg.type]p3:
6538 // If a declaration acquires a function type through a
6539 // type dependent on a template-parameter and this causes
6540 // a declaration that does not use the syntactic form of a
6541 // function declarator to have a function type, the program
6542 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006543 if (!T->isFunctionType()) {
6544 Diag(Loc, diag::err_unexpected_friend);
6545
6546 // It might be worthwhile to try to recover by creating an
6547 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006548 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006549 }
6550
6551 // C++ [namespace.memdef]p3
6552 // - If a friend declaration in a non-local class first declares a
6553 // class or function, the friend class or function is a member
6554 // of the innermost enclosing namespace.
6555 // - The name of the friend is not found by simple name lookup
6556 // until a matching declaration is provided in that namespace
6557 // scope (either before or after the class declaration granting
6558 // friendship).
6559 // - If a friend function is called, its name may be found by the
6560 // name lookup that considers functions from namespaces and
6561 // classes associated with the types of the function arguments.
6562 // - When looking for a prior declaration of a class or a function
6563 // declared as a friend, scopes outside the innermost enclosing
6564 // namespace scope are not considered.
6565
John McCallde3fd222010-10-12 23:13:28 +00006566 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006567 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6568 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006569 assert(Name);
6570
Douglas Gregor6c110f32010-12-16 01:14:37 +00006571 // Check for unexpanded parameter packs.
6572 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6573 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6574 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6575 return 0;
6576
John McCall07e91c02009-08-06 02:15:43 +00006577 // The context we found the declaration in, or in which we should
6578 // create the declaration.
6579 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006580 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006581 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006582 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006583
John McCallde3fd222010-10-12 23:13:28 +00006584 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006585
John McCallde3fd222010-10-12 23:13:28 +00006586 // There are four cases here.
6587 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006588 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006589 // there as appropriate.
6590 // Recover from invalid scope qualifiers as if they just weren't there.
6591 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006592 // C++0x [namespace.memdef]p3:
6593 // If the name in a friend declaration is neither qualified nor
6594 // a template-id and the declaration is a function or an
6595 // elaborated-type-specifier, the lookup to determine whether
6596 // the entity has been previously declared shall not consider
6597 // any scopes outside the innermost enclosing namespace.
6598 // C++0x [class.friend]p11:
6599 // If a friend declaration appears in a local class and the name
6600 // specified is an unqualified name, a prior declaration is
6601 // looked up without considering scopes that are outside the
6602 // innermost enclosing non-class scope. For a friend function
6603 // declaration, if there is no prior declaration, the program is
6604 // ill-formed.
6605 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006606 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006607
John McCallf7cfb222010-10-13 05:45:15 +00006608 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006609 DC = CurContext;
6610 while (true) {
6611 // Skip class contexts. If someone can cite chapter and verse
6612 // for this behavior, that would be nice --- it's what GCC and
6613 // EDG do, and it seems like a reasonable intent, but the spec
6614 // really only says that checks for unqualified existing
6615 // declarations should stop at the nearest enclosing namespace,
6616 // not that they should only consider the nearest enclosing
6617 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006618 while (DC->isRecord())
6619 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006620
John McCall1f82f242009-11-18 22:49:29 +00006621 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006622
6623 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006624 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006625 break;
John McCallf7cfb222010-10-13 05:45:15 +00006626
John McCallf4776592010-10-14 22:22:28 +00006627 if (isTemplateId) {
6628 if (isa<TranslationUnitDecl>(DC)) break;
6629 } else {
6630 if (DC->isFileContext()) break;
6631 }
John McCall07e91c02009-08-06 02:15:43 +00006632 DC = DC->getParent();
6633 }
6634
6635 // C++ [class.friend]p1: A friend of a class is a function or
6636 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006637 // C++0x changes this for both friend types and functions.
6638 // Most C++ 98 compilers do seem to give an error here, so
6639 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006640 if (!Previous.empty() && DC->Equals(CurContext)
6641 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006642 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006643
John McCallccbc0322010-10-13 06:22:15 +00006644 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006645
John McCallde3fd222010-10-12 23:13:28 +00006646 // - There's a non-dependent scope specifier, in which case we
6647 // compute it and do a previous lookup there for a function
6648 // or function template.
6649 } else if (!SS.getScopeRep()->isDependent()) {
6650 DC = computeDeclContext(SS);
6651 if (!DC) return 0;
6652
6653 if (RequireCompleteDeclContext(SS, DC)) return 0;
6654
6655 LookupQualifiedName(Previous, DC);
6656
6657 // Ignore things found implicitly in the wrong scope.
6658 // TODO: better diagnostics for this case. Suggesting the right
6659 // qualified scope would be nice...
6660 LookupResult::Filter F = Previous.makeFilter();
6661 while (F.hasNext()) {
6662 NamedDecl *D = F.next();
6663 if (!DC->InEnclosingNamespaceSetOf(
6664 D->getDeclContext()->getRedeclContext()))
6665 F.erase();
6666 }
6667 F.done();
6668
6669 if (Previous.empty()) {
6670 D.setInvalidType();
6671 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6672 return 0;
6673 }
6674
6675 // C++ [class.friend]p1: A friend of a class is a function or
6676 // class that is not a member of the class . . .
6677 if (DC->Equals(CurContext))
6678 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6679
6680 // - There's a scope specifier that does not match any template
6681 // parameter lists, in which case we use some arbitrary context,
6682 // create a method or method template, and wait for instantiation.
6683 // - There's a scope specifier that does match some template
6684 // parameter lists, which we don't handle right now.
6685 } else {
6686 DC = CurContext;
6687 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006688 }
6689
John McCallf7cfb222010-10-13 05:45:15 +00006690 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006691 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006692 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6693 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6694 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006695 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006696 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6697 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006698 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006699 }
John McCall07e91c02009-08-06 02:15:43 +00006700 }
6701
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006702 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006703 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006704 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006705 IsDefinition,
6706 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006707 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006708
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006709 assert(ND->getDeclContext() == DC);
6710 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006711
John McCall759e32b2009-08-31 22:39:49 +00006712 // Add the function declaration to the appropriate lookup tables,
6713 // adjusting the redeclarations list as necessary. We don't
6714 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006715 //
John McCall759e32b2009-08-31 22:39:49 +00006716 // Also update the scope-based lookup if the target context's
6717 // lookup context is in lexical scope.
6718 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006719 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006720 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006721 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006722 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006723 }
John McCallaa74a0c2009-08-28 07:59:38 +00006724
6725 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006726 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006727 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006728 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006729 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006730
John McCallde3fd222010-10-12 23:13:28 +00006731 if (ND->isInvalidDecl())
6732 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006733 else {
6734 FunctionDecl *FD;
6735 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6736 FD = FTD->getTemplatedDecl();
6737 else
6738 FD = cast<FunctionDecl>(ND);
6739
6740 // Mark templated-scope function declarations as unsupported.
6741 if (FD->getNumTemplateParameterLists())
6742 FrD->setUnsupportedFriend(true);
6743 }
John McCallde3fd222010-10-12 23:13:28 +00006744
John McCall48871652010-08-21 09:40:31 +00006745 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006746}
6747
John McCall48871652010-08-21 09:40:31 +00006748void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6749 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006750
Sebastian Redlf769df52009-03-24 22:27:57 +00006751 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6752 if (!Fn) {
6753 Diag(DelLoc, diag::err_deleted_non_function);
6754 return;
6755 }
6756 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6757 Diag(DelLoc, diag::err_deleted_decl_not_first);
6758 Diag(Prev->getLocation(), diag::note_previous_declaration);
6759 // If the declaration wasn't the first, we delete the function anyway for
6760 // recovery.
6761 }
6762 Fn->setDeleted();
6763}
Sebastian Redl4c018662009-04-27 21:33:24 +00006764
6765static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6766 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6767 ++CI) {
6768 Stmt *SubStmt = *CI;
6769 if (!SubStmt)
6770 continue;
6771 if (isa<ReturnStmt>(SubStmt))
6772 Self.Diag(SubStmt->getSourceRange().getBegin(),
6773 diag::err_return_in_constructor_handler);
6774 if (!isa<Expr>(SubStmt))
6775 SearchForReturnInStmt(Self, SubStmt);
6776 }
6777}
6778
6779void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6780 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6781 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6782 SearchForReturnInStmt(*this, Handler);
6783 }
6784}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006785
Mike Stump11289f42009-09-09 15:08:12 +00006786bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006787 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006788 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6789 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006790
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006791 if (Context.hasSameType(NewTy, OldTy) ||
6792 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006793 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006794
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006795 // Check if the return types are covariant
6796 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006797
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006798 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006799 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6800 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006801 NewClassTy = NewPT->getPointeeType();
6802 OldClassTy = OldPT->getPointeeType();
6803 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006804 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6805 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6806 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6807 NewClassTy = NewRT->getPointeeType();
6808 OldClassTy = OldRT->getPointeeType();
6809 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006810 }
6811 }
Mike Stump11289f42009-09-09 15:08:12 +00006812
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006813 // The return types aren't either both pointers or references to a class type.
6814 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006815 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006816 diag::err_different_return_type_for_overriding_virtual_function)
6817 << New->getDeclName() << NewTy << OldTy;
6818 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006819
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006820 return true;
6821 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006822
Anders Carlssone60365b2009-12-31 18:34:24 +00006823 // C++ [class.virtual]p6:
6824 // If the return type of D::f differs from the return type of B::f, the
6825 // class type in the return type of D::f shall be complete at the point of
6826 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006827 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6828 if (!RT->isBeingDefined() &&
6829 RequireCompleteType(New->getLocation(), NewClassTy,
6830 PDiag(diag::err_covariant_return_incomplete)
6831 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006832 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006833 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006834
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006835 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006836 // Check if the new class derives from the old class.
6837 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6838 Diag(New->getLocation(),
6839 diag::err_covariant_return_not_derived)
6840 << New->getDeclName() << NewTy << OldTy;
6841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6842 return true;
6843 }
Mike Stump11289f42009-09-09 15:08:12 +00006844
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006845 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006846 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006847 diag::err_covariant_return_inaccessible_base,
6848 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6849 // FIXME: Should this point to the return type?
6850 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006851 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6852 return true;
6853 }
6854 }
Mike Stump11289f42009-09-09 15:08:12 +00006855
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006856 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006857 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006858 Diag(New->getLocation(),
6859 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006860 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006861 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6862 return true;
6863 };
Mike Stump11289f42009-09-09 15:08:12 +00006864
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006865
6866 // The new class type must have the same or less qualifiers as the old type.
6867 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6868 Diag(New->getLocation(),
6869 diag::err_covariant_return_type_class_type_more_qualified)
6870 << New->getDeclName() << NewTy << OldTy;
6871 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6872 return true;
6873 };
Mike Stump11289f42009-09-09 15:08:12 +00006874
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006875 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006876}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006877
Alexis Hunt96d5c762009-11-21 08:43:09 +00006878bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6879 const CXXMethodDecl *Old)
6880{
6881 if (Old->hasAttr<FinalAttr>()) {
6882 Diag(New->getLocation(), diag::err_final_function_overridden)
6883 << New->getDeclName();
6884 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6885 return true;
6886 }
6887
6888 return false;
6889}
6890
Douglas Gregor21920e372009-12-01 17:24:26 +00006891/// \brief Mark the given method pure.
6892///
6893/// \param Method the method to be marked pure.
6894///
6895/// \param InitRange the source range that covers the "0" initializer.
6896bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6897 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6898 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006899 return false;
6900 }
6901
6902 if (!Method->isInvalidDecl())
6903 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6904 << Method->getDeclName() << InitRange;
6905 return true;
6906}
6907
John McCall1f4ee7b2009-12-19 09:28:58 +00006908/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6909/// an initializer for the out-of-line declaration 'Dcl'. The scope
6910/// is a fresh scope pushed for just this purpose.
6911///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006912/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6913/// static data member of class X, names should be looked up in the scope of
6914/// class X.
John McCall48871652010-08-21 09:40:31 +00006915void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006916 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006917 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006918
John McCall1f4ee7b2009-12-19 09:28:58 +00006919 // We should only get called for declarations with scope specifiers, like:
6920 // int foo::bar;
6921 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006922 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006923}
6924
6925/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006926/// initializer for the out-of-line declaration 'D'.
6927void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006928 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006929 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006930
John McCall1f4ee7b2009-12-19 09:28:58 +00006931 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006932 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006933}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006934
6935/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6936/// C++ if/switch/while/for statement.
6937/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006938DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006939 // C++ 6.4p2:
6940 // The declarator shall not specify a function or an array.
6941 // The type-specifier-seq shall not contain typedef and shall not declare a
6942 // new class or enumeration.
6943 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6944 "Parser allowed 'typedef' as storage class of condition decl.");
6945
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006946 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006947 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6948 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006949
6950 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6951 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6952 // would be created and CXXConditionDeclExpr wants a VarDecl.
6953 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6954 << D.getSourceRange();
6955 return DeclResult();
6956 } else if (OwnedTag && OwnedTag->isDefinition()) {
6957 // The type-specifier-seq shall not declare a new class or enumeration.
6958 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6959 }
6960
John McCall48871652010-08-21 09:40:31 +00006961 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006962 if (!Dcl)
6963 return DeclResult();
6964
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006965 return Dcl;
6966}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006967
Douglas Gregor88d292c2010-05-13 16:44:06 +00006968void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6969 bool DefinitionRequired) {
6970 // Ignore any vtable uses in unevaluated operands or for classes that do
6971 // not have a vtable.
6972 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6973 CurContext->isDependentContext() ||
6974 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006975 return;
6976
Douglas Gregor88d292c2010-05-13 16:44:06 +00006977 // Try to insert this class into the map.
6978 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6979 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6980 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6981 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006982 // If we already had an entry, check to see if we are promoting this vtable
6983 // to required a definition. If so, we need to reappend to the VTableUses
6984 // list, since we may have already processed the first entry.
6985 if (DefinitionRequired && !Pos.first->second) {
6986 Pos.first->second = true;
6987 } else {
6988 // Otherwise, we can early exit.
6989 return;
6990 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006991 }
6992
6993 // Local classes need to have their virtual members marked
6994 // immediately. For all other classes, we mark their virtual members
6995 // at the end of the translation unit.
6996 if (Class->isLocalClass())
6997 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006998 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006999 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007000}
7001
Douglas Gregor88d292c2010-05-13 16:44:06 +00007002bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007003 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007004 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007005
Douglas Gregor88d292c2010-05-13 16:44:06 +00007006 // Note: The VTableUses vector could grow as a result of marking
7007 // the members of a class as "used", so we check the size each
7008 // time through the loop and prefer indices (with are stable) to
7009 // iterators (which are not).
7010 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007011 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007012 if (!Class)
7013 continue;
7014
7015 SourceLocation Loc = VTableUses[I].second;
7016
7017 // If this class has a key function, but that key function is
7018 // defined in another translation unit, we don't need to emit the
7019 // vtable even though we're using it.
7020 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007021 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007022 switch (KeyFunction->getTemplateSpecializationKind()) {
7023 case TSK_Undeclared:
7024 case TSK_ExplicitSpecialization:
7025 case TSK_ExplicitInstantiationDeclaration:
7026 // The key function is in another translation unit.
7027 continue;
7028
7029 case TSK_ExplicitInstantiationDefinition:
7030 case TSK_ImplicitInstantiation:
7031 // We will be instantiating the key function.
7032 break;
7033 }
7034 } else if (!KeyFunction) {
7035 // If we have a class with no key function that is the subject
7036 // of an explicit instantiation declaration, suppress the
7037 // vtable; it will live with the explicit instantiation
7038 // definition.
7039 bool IsExplicitInstantiationDeclaration
7040 = Class->getTemplateSpecializationKind()
7041 == TSK_ExplicitInstantiationDeclaration;
7042 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7043 REnd = Class->redecls_end();
7044 R != REnd; ++R) {
7045 TemplateSpecializationKind TSK
7046 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7047 if (TSK == TSK_ExplicitInstantiationDeclaration)
7048 IsExplicitInstantiationDeclaration = true;
7049 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7050 IsExplicitInstantiationDeclaration = false;
7051 break;
7052 }
7053 }
7054
7055 if (IsExplicitInstantiationDeclaration)
7056 continue;
7057 }
7058
7059 // Mark all of the virtual members of this class as referenced, so
7060 // that we can build a vtable. Then, tell the AST consumer that a
7061 // vtable for this class is required.
7062 MarkVirtualMembersReferenced(Loc, Class);
7063 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7064 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7065
7066 // Optionally warn if we're emitting a weak vtable.
7067 if (Class->getLinkage() == ExternalLinkage &&
7068 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007069 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007070 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7071 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007072 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007073 VTableUses.clear();
7074
Anders Carlsson82fccd02009-12-07 08:24:59 +00007075 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007076}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007077
Rafael Espindola5b334082010-03-26 00:36:59 +00007078void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7079 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007080 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7081 e = RD->method_end(); i != e; ++i) {
7082 CXXMethodDecl *MD = *i;
7083
7084 // C++ [basic.def.odr]p2:
7085 // [...] A virtual member function is used if it is not pure. [...]
7086 if (MD->isVirtual() && !MD->isPure())
7087 MarkDeclarationReferenced(Loc, MD);
7088 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007089
7090 // Only classes that have virtual bases need a VTT.
7091 if (RD->getNumVBases() == 0)
7092 return;
7093
7094 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7095 e = RD->bases_end(); i != e; ++i) {
7096 const CXXRecordDecl *Base =
7097 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007098 if (Base->getNumVBases() == 0)
7099 continue;
7100 MarkVirtualMembersReferenced(Loc, Base);
7101 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007102}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007103
7104/// SetIvarInitializers - This routine builds initialization ASTs for the
7105/// Objective-C implementation whose ivars need be initialized.
7106void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7107 if (!getLangOptions().CPlusPlus)
7108 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007109 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007110 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7111 CollectIvarsToConstructOrDestruct(OID, ivars);
7112 if (ivars.empty())
7113 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007114 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007115 for (unsigned i = 0; i < ivars.size(); i++) {
7116 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007117 if (Field->isInvalidDecl())
7118 continue;
7119
Alexis Hunt1d792652011-01-08 20:30:50 +00007120 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007121 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7122 InitializationKind InitKind =
7123 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7124
7125 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007126 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007127 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007128 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007129 // Note, MemberInit could actually come back empty if no initialization
7130 // is required (e.g., because it would call a trivial default constructor)
7131 if (!MemberInit.get() || MemberInit.isInvalid())
7132 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007133
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007134 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007135 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7136 SourceLocation(),
7137 MemberInit.takeAs<Expr>(),
7138 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007139 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007140
7141 // Be sure that the destructor is accessible and is marked as referenced.
7142 if (const RecordType *RecordTy
7143 = Context.getBaseElementType(Field->getType())
7144 ->getAs<RecordType>()) {
7145 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007146 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007147 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7148 CheckDestructorAccess(Field->getLocation(), Destructor,
7149 PDiag(diag::err_access_dtor_ivar)
7150 << Context.getBaseElementType(Field->getType()));
7151 }
7152 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007153 }
7154 ObjCImplementation->setIvarInitializers(Context,
7155 AllToInit.data(), AllToInit.size());
7156 }
7157}