blob: c58fbce5de8f5edffe9135584876895f66a8a1f4 [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,
Anders Carlssondb36b802011-01-20 03:57:25 +0000862 ExprTy *BW, const VirtSpecifiers &VS,
863 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000864 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000865 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000866 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
867 DeclarationName Name = NameInfo.getName();
868 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000869
870 // For anonymous bitfields, the location should point to the type.
871 if (Loc.isInvalid())
872 Loc = D.getSourceRange().getBegin();
873
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000874 Expr *BitWidth = static_cast<Expr*>(BW);
875 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876
John McCallb1cd7da2010-06-04 08:34:12 +0000877 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000878 assert(!DS.isFriendSpecified());
879
John McCallb1cd7da2010-06-04 08:34:12 +0000880 bool isFunc = false;
881 if (D.isFunctionDeclarator())
882 isFunc = true;
883 else if (D.getNumTypeObjects() == 0 &&
884 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000885 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000886 isFunc = TDType->isFunctionType();
887 }
888
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000889 // C++ 9.2p6: A member shall not be declared to have automatic storage
890 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000891 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
892 // data members and cannot be applied to names declared const or static,
893 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 switch (DS.getStorageClassSpec()) {
895 case DeclSpec::SCS_unspecified:
896 case DeclSpec::SCS_typedef:
897 case DeclSpec::SCS_static:
898 // FALL THROUGH.
899 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000900 case DeclSpec::SCS_mutable:
901 if (isFunc) {
902 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000903 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000904 else
Chris Lattner3b054132008-11-19 05:08:23 +0000905 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Sebastian Redl8071edb2008-11-17 23:24:37 +0000907 // FIXME: It would be nicer if the keyword was ignored only for this
908 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000909 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000910 }
911 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000912 default:
913 if (DS.getStorageClassSpecLoc().isValid())
914 Diag(DS.getStorageClassSpecLoc(),
915 diag::err_storageclass_invalid_for_member);
916 else
917 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
918 D.getMutableDeclSpec().ClearStorageClassSpecs();
919 }
920
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000921 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
922 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000923 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000924
925 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000926 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000927 CXXScopeSpec &SS = D.getCXXScopeSpec();
928
929
930 if (SS.isSet() && !SS.isInvalid()) {
931 // The user provided a superfluous scope specifier inside a class
932 // definition:
933 //
934 // class X {
935 // int X::member;
936 // };
937 DeclContext *DC = 0;
938 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
939 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
940 << Name << FixItHint::CreateRemoval(SS.getRange());
941 else
942 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
943 << Name << SS.getRange();
944
945 SS.clear();
946 }
947
Douglas Gregor3447e762009-08-20 22:52:58 +0000948 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000949 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000950 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
951 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000952 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000953 } else {
John McCall48871652010-08-21 09:40:31 +0000954 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000955 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000956 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000957 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000958
959 // Non-instance-fields can't have a bitfield.
960 if (BitWidth) {
961 if (Member->isInvalidDecl()) {
962 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000963 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000964 // C++ 9.6p3: A bit-field shall not be a static member.
965 // "static member 'A' cannot be a bit-field"
966 Diag(Loc, diag::err_static_not_bitfield)
967 << Name << BitWidth->getSourceRange();
968 } else if (isa<TypedefDecl>(Member)) {
969 // "typedef member 'x' cannot be a bit-field"
970 Diag(Loc, diag::err_typedef_not_bitfield)
971 << Name << BitWidth->getSourceRange();
972 } else {
973 // A function typedef ("typedef int f(); f a;").
974 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
975 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000976 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000977 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Chris Lattnerd26760a2009-03-05 23:01:03 +0000980 BitWidth = 0;
981 Member->setInvalidDecl();
982 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000983
984 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregor3447e762009-08-20 22:52:58 +0000986 // If we have declared a member function template, set the access of the
987 // templated declaration as well.
988 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
989 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000990 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000991
Anders Carlsson13a69102011-01-20 04:34:22 +0000992 if (VS.isOverrideSpecified()) {
993 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
994 if (!MD || !MD->isVirtual()) {
995 Diag(Member->getLocStart(),
996 diag::override_keyword_only_allowed_on_virtual_member_functions)
997 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
998 }
999 }
1000 if (VS.isFinalSpecified()) {
1001 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1002 if (!MD || !MD->isVirtual()) {
1003 Diag(Member->getLocStart(),
1004 diag::override_keyword_only_allowed_on_virtual_member_functions)
1005 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1006 }
1007 }
Douglas Gregor92751d42008-11-17 22:58:34 +00001008 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001009
Douglas Gregor0c880302009-03-11 23:00:04 +00001010 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001011 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001012 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001013 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001014
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001015 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001016 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001017 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001018 }
John McCall48871652010-08-21 09:40:31 +00001019 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001020}
1021
Douglas Gregor15e77a22009-12-31 09:10:24 +00001022/// \brief Find the direct and/or virtual base specifiers that
1023/// correspond to the given base type, for use in base initialization
1024/// within a constructor.
1025static bool FindBaseInitializer(Sema &SemaRef,
1026 CXXRecordDecl *ClassDecl,
1027 QualType BaseType,
1028 const CXXBaseSpecifier *&DirectBaseSpec,
1029 const CXXBaseSpecifier *&VirtualBaseSpec) {
1030 // First, check for a direct base class.
1031 DirectBaseSpec = 0;
1032 for (CXXRecordDecl::base_class_const_iterator Base
1033 = ClassDecl->bases_begin();
1034 Base != ClassDecl->bases_end(); ++Base) {
1035 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1036 // We found a direct base of this type. That's what we're
1037 // initializing.
1038 DirectBaseSpec = &*Base;
1039 break;
1040 }
1041 }
1042
1043 // Check for a virtual base class.
1044 // FIXME: We might be able to short-circuit this if we know in advance that
1045 // there are no virtual bases.
1046 VirtualBaseSpec = 0;
1047 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1048 // We haven't found a base yet; search the class hierarchy for a
1049 // virtual base class.
1050 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1051 /*DetectVirtual=*/false);
1052 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1053 BaseType, Paths)) {
1054 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1055 Path != Paths.end(); ++Path) {
1056 if (Path->back().Base->isVirtual()) {
1057 VirtualBaseSpec = Path->back().Base;
1058 break;
1059 }
1060 }
1061 }
1062 }
1063
1064 return DirectBaseSpec || VirtualBaseSpec;
1065}
1066
Douglas Gregore8381c02008-11-05 04:29:56 +00001067/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001068MemInitResult
John McCall48871652010-08-21 09:40:31 +00001069Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001070 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001071 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001072 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001073 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001074 SourceLocation IdLoc,
1075 SourceLocation LParenLoc,
1076 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001077 SourceLocation RParenLoc,
1078 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001079 if (!ConstructorD)
1080 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001082 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001083
1084 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001085 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001086 if (!Constructor) {
1087 // The user wrote a constructor initializer on a function that is
1088 // not a C++ constructor. Ignore the error for now, because we may
1089 // have more member initializers coming; we'll diagnose it just
1090 // once in ActOnMemInitializers.
1091 return true;
1092 }
1093
1094 CXXRecordDecl *ClassDecl = Constructor->getParent();
1095
1096 // C++ [class.base.init]p2:
1097 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001098 // constructor's class and, if not found in that scope, are looked
1099 // up in the scope containing the constructor's definition.
1100 // [Note: if the constructor's class contains a member with the
1101 // same name as a direct or virtual base class of the class, a
1102 // mem-initializer-id naming the member or base class and composed
1103 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001104 // mem-initializer-id for the hidden base class may be specified
1105 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001106 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001107 // Look for a member, first.
1108 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001109 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001110 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001111 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001112 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001113
Douglas Gregor44e7df62011-01-04 00:32:56 +00001114 if (Member) {
1115 if (EllipsisLoc.isValid())
1116 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1117 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1118
Francois Pichetd583da02010-12-04 09:14:42 +00001119 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001120 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001121 }
1122
Francois Pichetd583da02010-12-04 09:14:42 +00001123 // Handle anonymous union case.
1124 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001125 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1126 if (EllipsisLoc.isValid())
1127 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1128 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1129
Francois Pichetd583da02010-12-04 09:14:42 +00001130 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1131 NumArgs, IdLoc,
1132 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001133 }
Francois Pichetd583da02010-12-04 09:14:42 +00001134 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001135 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001136 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001137 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001138 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001139
1140 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001141 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001142 } else {
1143 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1144 LookupParsedName(R, S, &SS);
1145
1146 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1147 if (!TyD) {
1148 if (R.isAmbiguous()) return true;
1149
John McCallda6841b2010-04-09 19:01:14 +00001150 // We don't want access-control diagnostics here.
1151 R.suppressDiagnostics();
1152
Douglas Gregora3b624a2010-01-19 06:46:48 +00001153 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1154 bool NotUnknownSpecialization = false;
1155 DeclContext *DC = computeDeclContext(SS, false);
1156 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1157 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1158
1159 if (!NotUnknownSpecialization) {
1160 // When the scope specifier can refer to a member of an unknown
1161 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001162 BaseType = CheckTypenameType(ETK_None,
1163 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001164 *MemberOrBase, SourceLocation(),
1165 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001166 if (BaseType.isNull())
1167 return true;
1168
Douglas Gregora3b624a2010-01-19 06:46:48 +00001169 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001170 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001171 }
1172 }
1173
Douglas Gregor15e77a22009-12-31 09:10:24 +00001174 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001175 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001176 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1177 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001178 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001179 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001180 // We have found a non-static data member with a similar
1181 // name to what was typed; complain and initialize that
1182 // member.
1183 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1184 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001185 << FixItHint::CreateReplacement(R.getNameLoc(),
1186 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001187 Diag(Member->getLocation(), diag::note_previous_decl)
1188 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001189
1190 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1191 LParenLoc, RParenLoc);
1192 }
1193 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1194 const CXXBaseSpecifier *DirectBaseSpec;
1195 const CXXBaseSpecifier *VirtualBaseSpec;
1196 if (FindBaseInitializer(*this, ClassDecl,
1197 Context.getTypeDeclType(Type),
1198 DirectBaseSpec, VirtualBaseSpec)) {
1199 // We have found a direct or virtual base class with a
1200 // similar name to what was typed; complain and initialize
1201 // that base class.
1202 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1203 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001204 << FixItHint::CreateReplacement(R.getNameLoc(),
1205 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001206
1207 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1208 : VirtualBaseSpec;
1209 Diag(BaseSpec->getSourceRange().getBegin(),
1210 diag::note_base_class_specified_here)
1211 << BaseSpec->getType()
1212 << BaseSpec->getSourceRange();
1213
Douglas Gregor15e77a22009-12-31 09:10:24 +00001214 TyD = Type;
1215 }
1216 }
1217 }
1218
Douglas Gregora3b624a2010-01-19 06:46:48 +00001219 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001220 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1221 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1222 return true;
1223 }
John McCallb5a0d312009-12-21 10:41:20 +00001224 }
1225
Douglas Gregora3b624a2010-01-19 06:46:48 +00001226 if (BaseType.isNull()) {
1227 BaseType = Context.getTypeDeclType(TyD);
1228 if (SS.isSet()) {
1229 NestedNameSpecifier *Qualifier =
1230 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001231
Douglas Gregora3b624a2010-01-19 06:46:48 +00001232 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001233 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001234 }
John McCallb5a0d312009-12-21 10:41:20 +00001235 }
1236 }
Mike Stump11289f42009-09-09 15:08:12 +00001237
John McCallbcd03502009-12-07 02:54:59 +00001238 if (!TInfo)
1239 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001240
John McCallbcd03502009-12-07 02:54:59 +00001241 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001242 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001243}
1244
John McCalle22a04a2009-11-04 23:02:40 +00001245/// Checks an initializer expression for use of uninitialized fields, such as
1246/// containing the field that is being initialized. Returns true if there is an
1247/// uninitialized field was used an updates the SourceLocation parameter; false
1248/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001249static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001250 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001251 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001252 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1253
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001254 if (isa<CallExpr>(S)) {
1255 // Do not descend into function calls or constructors, as the use
1256 // of an uninitialized field may be valid. One would have to inspect
1257 // the contents of the function/ctor to determine if it is safe or not.
1258 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1259 // may be safe, depending on what the function/ctor does.
1260 return false;
1261 }
1262 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1263 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001264
1265 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1266 // The member expression points to a static data member.
1267 assert(VD->isStaticDataMember() &&
1268 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001269 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001270 return false;
1271 }
1272
1273 if (isa<EnumConstantDecl>(RhsField)) {
1274 // The member expression points to an enum.
1275 return false;
1276 }
1277
John McCalle22a04a2009-11-04 23:02:40 +00001278 if (RhsField == LhsField) {
1279 // Initializing a field with itself. Throw a warning.
1280 // But wait; there are exceptions!
1281 // Exception #1: The field may not belong to this record.
1282 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001283 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001284 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1285 // Even though the field matches, it does not belong to this record.
1286 return false;
1287 }
1288 // None of the exceptions triggered; return true to indicate an
1289 // uninitialized field was used.
1290 *L = ME->getMemberLoc();
1291 return true;
1292 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001293 } else if (isa<SizeOfAlignOfExpr>(S)) {
1294 // sizeof/alignof doesn't reference contents, do not warn.
1295 return false;
1296 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1297 // address-of doesn't reference contents (the pointer may be dereferenced
1298 // in the same expression but it would be rare; and weird).
1299 if (UOE->getOpcode() == UO_AddrOf)
1300 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001301 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001302 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1303 it != e; ++it) {
1304 if (!*it) {
1305 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001306 continue;
1307 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001308 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1309 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001310 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001311 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001312}
1313
John McCallfaf5fb42010-08-26 23:41:50 +00001314MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001315Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001316 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001317 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001318 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001319 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1320 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1321 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001322 "Member must be a FieldDecl or IndirectFieldDecl");
1323
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001324 if (Member->isInvalidDecl())
1325 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001326
John McCalle22a04a2009-11-04 23:02:40 +00001327 // Diagnose value-uses of fields to initialize themselves, e.g.
1328 // foo(foo)
1329 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001330 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001331 for (unsigned i = 0; i < NumArgs; ++i) {
1332 SourceLocation L;
1333 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1334 // FIXME: Return true in the case when other fields are used before being
1335 // uninitialized. For example, let this field be the i'th field. When
1336 // initializing the i'th field, throw a warning if any of the >= i'th
1337 // fields are used, as they are not yet initialized.
1338 // Right now we are only handling the case where the i'th field uses
1339 // itself in its initializer.
1340 Diag(L, diag::warn_field_is_uninit);
1341 }
1342 }
1343
Eli Friedman8e1433b2009-07-29 19:44:27 +00001344 bool HasDependentArg = false;
1345 for (unsigned i = 0; i < NumArgs; i++)
1346 HasDependentArg |= Args[i]->isTypeDependent();
1347
Chandler Carruthd44c3102010-12-06 09:23:57 +00001348 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001349 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001350 // Can't check initialization for a member of dependent type or when
1351 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001352 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1353 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001354
1355 // Erase any temporaries within this evaluation context; we're not
1356 // going to track them in the AST, since we'll be rebuilding the
1357 // ASTs during template instantiation.
1358 ExprTemporaries.erase(
1359 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1360 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001361 } else {
1362 // Initialize the member.
1363 InitializedEntity MemberEntity =
1364 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1365 : InitializedEntity::InitializeMember(IndirectMember, 0);
1366 InitializationKind Kind =
1367 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001368
Chandler Carruthd44c3102010-12-06 09:23:57 +00001369 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1370
1371 ExprResult MemberInit =
1372 InitSeq.Perform(*this, MemberEntity, Kind,
1373 MultiExprArg(*this, Args, NumArgs), 0);
1374 if (MemberInit.isInvalid())
1375 return true;
1376
1377 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1378
1379 // C++0x [class.base.init]p7:
1380 // The initialization of each base and member constitutes a
1381 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001382 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001383 if (MemberInit.isInvalid())
1384 return true;
1385
1386 // If we are in a dependent context, template instantiation will
1387 // perform this type-checking again. Just save the arguments that we
1388 // received in a ParenListExpr.
1389 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1390 // of the information that we have about the member
1391 // initializer. However, deconstructing the ASTs is a dicey process,
1392 // and this approach is far more likely to get the corner cases right.
1393 if (CurContext->isDependentContext())
1394 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1395 RParenLoc);
1396 else
1397 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001398 }
1399
Chandler Carruthd44c3102010-12-06 09:23:57 +00001400 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001401 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001402 IdLoc, LParenLoc, Init,
1403 RParenLoc);
1404 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001405 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001406 IdLoc, LParenLoc, Init,
1407 RParenLoc);
1408 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001409}
1410
John McCallfaf5fb42010-08-26 23:41:50 +00001411MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001412Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1413 Expr **Args, unsigned NumArgs,
1414 SourceLocation LParenLoc,
1415 SourceLocation RParenLoc,
1416 CXXRecordDecl *ClassDecl,
1417 SourceLocation EllipsisLoc) {
1418 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1419 if (!LangOpts.CPlusPlus0x)
1420 return Diag(Loc, diag::err_delegation_0x_only)
1421 << TInfo->getTypeLoc().getLocalSourceRange();
1422
1423 return Diag(Loc, diag::err_delegation_unimplemented)
1424 << TInfo->getTypeLoc().getLocalSourceRange();
1425}
1426
1427MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001428Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001429 Expr **Args, unsigned NumArgs,
1430 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001431 CXXRecordDecl *ClassDecl,
1432 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001433 bool HasDependentArg = false;
1434 for (unsigned i = 0; i < NumArgs; i++)
1435 HasDependentArg |= Args[i]->isTypeDependent();
1436
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001437 SourceLocation BaseLoc
1438 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1439
1440 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1441 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1442 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1443
1444 // C++ [class.base.init]p2:
1445 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001446 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001447 // of that class, the mem-initializer is ill-formed. A
1448 // mem-initializer-list can initialize a base class using any
1449 // name that denotes that base class type.
1450 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1451
Douglas Gregor44e7df62011-01-04 00:32:56 +00001452 if (EllipsisLoc.isValid()) {
1453 // This is a pack expansion.
1454 if (!BaseType->containsUnexpandedParameterPack()) {
1455 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1456 << SourceRange(BaseLoc, RParenLoc);
1457
1458 EllipsisLoc = SourceLocation();
1459 }
1460 } else {
1461 // Check for any unexpanded parameter packs.
1462 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1463 return true;
1464
1465 for (unsigned I = 0; I != NumArgs; ++I)
1466 if (DiagnoseUnexpandedParameterPack(Args[I]))
1467 return true;
1468 }
1469
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001470 // Check for direct and virtual base classes.
1471 const CXXBaseSpecifier *DirectBaseSpec = 0;
1472 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1473 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001474 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1475 BaseType))
1476 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1477 LParenLoc, RParenLoc, ClassDecl,
1478 EllipsisLoc);
1479
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001480 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1481 VirtualBaseSpec);
1482
1483 // C++ [base.class.init]p2:
1484 // Unless the mem-initializer-id names a nonstatic data member of the
1485 // constructor's class or a direct or virtual base of that class, the
1486 // mem-initializer is ill-formed.
1487 if (!DirectBaseSpec && !VirtualBaseSpec) {
1488 // If the class has any dependent bases, then it's possible that
1489 // one of those types will resolve to the same type as
1490 // BaseType. Therefore, just treat this as a dependent base
1491 // class initialization. FIXME: Should we try to check the
1492 // initialization anyway? It seems odd.
1493 if (ClassDecl->hasAnyDependentBases())
1494 Dependent = true;
1495 else
1496 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1497 << BaseType << Context.getTypeDeclType(ClassDecl)
1498 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1499 }
1500 }
1501
1502 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001503 // Can't check initialization for a base of dependent type or when
1504 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001505 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001506 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1507 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001508
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001509 // Erase any temporaries within this evaluation context; we're not
1510 // going to track them in the AST, since we'll be rebuilding the
1511 // ASTs during template instantiation.
1512 ExprTemporaries.erase(
1513 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1514 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001515
Alexis Hunt1d792652011-01-08 20:30:50 +00001516 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001517 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001518 LParenLoc,
1519 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001520 RParenLoc,
1521 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001522 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001523
1524 // C++ [base.class.init]p2:
1525 // If a mem-initializer-id is ambiguous because it designates both
1526 // a direct non-virtual base class and an inherited virtual base
1527 // class, the mem-initializer is ill-formed.
1528 if (DirectBaseSpec && VirtualBaseSpec)
1529 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001530 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001531
1532 CXXBaseSpecifier *BaseSpec
1533 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1534 if (!BaseSpec)
1535 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1536
1537 // Initialize the base.
1538 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001539 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001540 InitializationKind Kind =
1541 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1542
1543 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1544
John McCalldadc5752010-08-24 06:29:42 +00001545 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001546 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001547 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001548 if (BaseInit.isInvalid())
1549 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001550
1551 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001552
1553 // C++0x [class.base.init]p7:
1554 // The initialization of each base and member constitutes a
1555 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001556 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001557 if (BaseInit.isInvalid())
1558 return true;
1559
1560 // If we are in a dependent context, template instantiation will
1561 // perform this type-checking again. Just save the arguments that we
1562 // received in a ParenListExpr.
1563 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1564 // of the information that we have about the base
1565 // initializer. However, deconstructing the ASTs is a dicey process,
1566 // and this approach is far more likely to get the corner cases right.
1567 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001568 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001569 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1570 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001571 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001572 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001573 LParenLoc,
1574 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001575 RParenLoc,
1576 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001577 }
1578
Alexis Hunt1d792652011-01-08 20:30:50 +00001579 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001580 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001581 LParenLoc,
1582 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001583 RParenLoc,
1584 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001585}
1586
Anders Carlsson1b00e242010-04-23 03:10:23 +00001587/// ImplicitInitializerKind - How an implicit base or member initializer should
1588/// initialize its base or member.
1589enum ImplicitInitializerKind {
1590 IIK_Default,
1591 IIK_Copy,
1592 IIK_Move
1593};
1594
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001595static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001596BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001597 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001598 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001599 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001600 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001601 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001602 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1603 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001604
John McCalldadc5752010-08-24 06:29:42 +00001605 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001606
1607 switch (ImplicitInitKind) {
1608 case IIK_Default: {
1609 InitializationKind InitKind
1610 = InitializationKind::CreateDefault(Constructor->getLocation());
1611 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1612 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001613 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001614 break;
1615 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001616
Anders Carlsson1b00e242010-04-23 03:10:23 +00001617 case IIK_Copy: {
1618 ParmVarDecl *Param = Constructor->getParamDecl(0);
1619 QualType ParamType = Param->getType().getNonReferenceType();
1620
1621 Expr *CopyCtorArg =
1622 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001623 Constructor->getLocation(), ParamType,
1624 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001625
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001626 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001627 QualType ArgTy =
1628 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1629 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001630
1631 CXXCastPath BasePath;
1632 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001633 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001634 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001635 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001636
Anders Carlsson1b00e242010-04-23 03:10:23 +00001637 InitializationKind InitKind
1638 = InitializationKind::CreateDirect(Constructor->getLocation(),
1639 SourceLocation(), SourceLocation());
1640 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1641 &CopyCtorArg, 1);
1642 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001643 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001644 break;
1645 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001646
Anders Carlsson1b00e242010-04-23 03:10:23 +00001647 case IIK_Move:
1648 assert(false && "Unhandled initializer kind!");
1649 }
John McCallb268a282010-08-23 23:25:46 +00001650
Douglas Gregora40433a2010-12-07 00:41:46 +00001651 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001652 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001653 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001654
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001655 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001656 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001657 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1658 SourceLocation()),
1659 BaseSpec->isVirtual(),
1660 SourceLocation(),
1661 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001662 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001663 SourceLocation());
1664
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001665 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001666}
1667
Anders Carlsson3c1db572010-04-23 02:15:47 +00001668static bool
1669BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001670 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001671 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001672 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001673 if (Field->isInvalidDecl())
1674 return true;
1675
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001676 SourceLocation Loc = Constructor->getLocation();
1677
Anders Carlsson423f5d82010-04-23 16:04:08 +00001678 if (ImplicitInitKind == IIK_Copy) {
1679 ParmVarDecl *Param = Constructor->getParamDecl(0);
1680 QualType ParamType = Param->getType().getNonReferenceType();
1681
1682 Expr *MemberExprBase =
1683 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001684 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001685
1686 // Build a reference to this field within the parameter.
1687 CXXScopeSpec SS;
1688 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1689 Sema::LookupMemberName);
1690 MemberLookup.addDecl(Field, AS_public);
1691 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001692 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001693 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001694 ParamType, Loc,
1695 /*IsArrow=*/false,
1696 SS,
1697 /*FirstQualifierInScope=*/0,
1698 MemberLookup,
1699 /*TemplateArgs=*/0);
1700 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001701 return true;
1702
Douglas Gregor94f9a482010-05-05 05:51:00 +00001703 // When the field we are copying is an array, create index variables for
1704 // each dimension of the array. We use these index variables to subscript
1705 // the source array, and other clients (e.g., CodeGen) will perform the
1706 // necessary iteration with these index variables.
1707 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1708 QualType BaseType = Field->getType();
1709 QualType SizeType = SemaRef.Context.getSizeType();
1710 while (const ConstantArrayType *Array
1711 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1712 // Create the iteration variable for this array index.
1713 IdentifierInfo *IterationVarName = 0;
1714 {
1715 llvm::SmallString<8> Str;
1716 llvm::raw_svector_ostream OS(Str);
1717 OS << "__i" << IndexVariables.size();
1718 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1719 }
1720 VarDecl *IterationVar
1721 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1722 IterationVarName, SizeType,
1723 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001724 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001725 IndexVariables.push_back(IterationVar);
1726
1727 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001728 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001729 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001730 assert(!IterationVarRef.isInvalid() &&
1731 "Reference to invented variable cannot fail!");
1732
1733 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001734 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001735 Loc,
John McCallb268a282010-08-23 23:25:46 +00001736 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001737 Loc);
1738 if (CopyCtorArg.isInvalid())
1739 return true;
1740
1741 BaseType = Array->getElementType();
1742 }
1743
1744 // Construct the entity that we will be initializing. For an array, this
1745 // will be first element in the array, which may require several levels
1746 // of array-subscript entities.
1747 llvm::SmallVector<InitializedEntity, 4> Entities;
1748 Entities.reserve(1 + IndexVariables.size());
1749 Entities.push_back(InitializedEntity::InitializeMember(Field));
1750 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1751 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1752 0,
1753 Entities.back()));
1754
1755 // Direct-initialize to use the copy constructor.
1756 InitializationKind InitKind =
1757 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1758
1759 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1760 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1761 &CopyCtorArgE, 1);
1762
John McCalldadc5752010-08-24 06:29:42 +00001763 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001764 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001765 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001766 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001767 if (MemberInit.isInvalid())
1768 return true;
1769
1770 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001771 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001772 MemberInit.takeAs<Expr>(), Loc,
1773 IndexVariables.data(),
1774 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001775 return false;
1776 }
1777
Anders Carlsson423f5d82010-04-23 16:04:08 +00001778 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1779
Anders Carlsson3c1db572010-04-23 02:15:47 +00001780 QualType FieldBaseElementType =
1781 SemaRef.Context.getBaseElementType(Field->getType());
1782
Anders Carlsson3c1db572010-04-23 02:15:47 +00001783 if (FieldBaseElementType->isRecordType()) {
1784 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001785 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001786 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001787
1788 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001789 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001790 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001791
Douglas Gregora40433a2010-12-07 00:41:46 +00001792 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001793 if (MemberInit.isInvalid())
1794 return true;
1795
1796 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001797 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001798 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001799 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001800 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001801 return false;
1802 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001803
1804 if (FieldBaseElementType->isReferenceType()) {
1805 SemaRef.Diag(Constructor->getLocation(),
1806 diag::err_uninitialized_member_in_ctor)
1807 << (int)Constructor->isImplicit()
1808 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1809 << 0 << Field->getDeclName();
1810 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1811 return true;
1812 }
1813
1814 if (FieldBaseElementType.isConstQualified()) {
1815 SemaRef.Diag(Constructor->getLocation(),
1816 diag::err_uninitialized_member_in_ctor)
1817 << (int)Constructor->isImplicit()
1818 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1819 << 1 << Field->getDeclName();
1820 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1821 return true;
1822 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001823
1824 // Nothing to initialize.
1825 CXXMemberInit = 0;
1826 return false;
1827}
John McCallbc83b3f2010-05-20 23:23:51 +00001828
1829namespace {
1830struct BaseAndFieldInfo {
1831 Sema &S;
1832 CXXConstructorDecl *Ctor;
1833 bool AnyErrorsInInits;
1834 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001835 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1836 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001837
1838 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1839 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1840 // FIXME: Handle implicit move constructors.
1841 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1842 IIK = IIK_Copy;
1843 else
1844 IIK = IIK_Default;
1845 }
1846};
1847}
1848
1849static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1850 FieldDecl *Top, FieldDecl *Field) {
1851
Chandler Carruth139e9622010-06-30 02:59:29 +00001852 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001853 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001854 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001855 return false;
1856 }
1857
1858 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1859 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1860 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001861 CXXRecordDecl *FieldClassDecl
1862 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001863
1864 // Even though union members never have non-trivial default
1865 // constructions in C++03, we still build member initializers for aggregate
1866 // record types which can be union members, and C++0x allows non-trivial
1867 // default constructors for union members, so we ensure that only one
1868 // member is initialized for these.
1869 if (FieldClassDecl->isUnion()) {
1870 // First check for an explicit initializer for one field.
1871 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1872 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001873 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001874 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001875
1876 // Once we've initialized a field of an anonymous union, the union
1877 // field in the class is also initialized, so exit immediately.
1878 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001879 } else if ((*FA)->isAnonymousStructOrUnion()) {
1880 if (CollectFieldInitializer(Info, Top, *FA))
1881 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001882 }
1883 }
1884
1885 // Fallthrough and construct a default initializer for the union as
1886 // a whole, which can call its default constructor if such a thing exists
1887 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1888 // behavior going forward with C++0x, when anonymous unions there are
1889 // finalized, we should revisit this.
1890 } else {
1891 // For structs, we simply descend through to initialize all members where
1892 // necessary.
1893 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1894 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1895 if (CollectFieldInitializer(Info, Top, *FA))
1896 return true;
1897 }
1898 }
John McCallbc83b3f2010-05-20 23:23:51 +00001899 }
1900
1901 // Don't try to build an implicit initializer if there were semantic
1902 // errors in any of the initializers (and therefore we might be
1903 // missing some that the user actually wrote).
1904 if (Info.AnyErrorsInInits)
1905 return false;
1906
Alexis Hunt1d792652011-01-08 20:30:50 +00001907 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001908 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1909 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001910
Francois Pichetd583da02010-12-04 09:14:42 +00001911 if (Init)
1912 Info.AllToInit.push_back(Init);
1913
John McCallbc83b3f2010-05-20 23:23:51 +00001914 return false;
1915}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001916
Eli Friedman9cf6b592009-11-09 19:20:36 +00001917bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001918Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1919 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001920 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001921 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001922 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001923 // Just store the initializers as written, they will be checked during
1924 // instantiation.
1925 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001926 Constructor->setNumCtorInitializers(NumInitializers);
1927 CXXCtorInitializer **baseOrMemberInitializers =
1928 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001929 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001930 NumInitializers * sizeof(CXXCtorInitializer*));
1931 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001932 }
1933
1934 return false;
1935 }
1936
John McCallbc83b3f2010-05-20 23:23:51 +00001937 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001938
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001939 // We need to build the initializer AST according to order of construction
1940 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001941 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001942 if (!ClassDecl)
1943 return true;
1944
Eli Friedman9cf6b592009-11-09 19:20:36 +00001945 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001946
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001947 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001948 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001949
1950 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001951 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001952 else
Francois Pichetd583da02010-12-04 09:14:42 +00001953 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001954 }
1955
Anders Carlsson43c64af2010-04-21 19:52:01 +00001956 // Keep track of the direct virtual bases.
1957 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1958 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1959 E = ClassDecl->bases_end(); I != E; ++I) {
1960 if (I->isVirtual())
1961 DirectVBases.insert(I);
1962 }
1963
Anders Carlssondb0a9652010-04-02 06:26:44 +00001964 // Push virtual bases before others.
1965 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1966 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1967
Alexis Hunt1d792652011-01-08 20:30:50 +00001968 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001969 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1970 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001971 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001972 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00001973 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001974 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001975 VBase, IsInheritedVirtualBase,
1976 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001977 HadError = true;
1978 continue;
1979 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001980
John McCallbc83b3f2010-05-20 23:23:51 +00001981 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001982 }
1983 }
Mike Stump11289f42009-09-09 15:08:12 +00001984
John McCallbc83b3f2010-05-20 23:23:51 +00001985 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001986 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1987 E = ClassDecl->bases_end(); Base != E; ++Base) {
1988 // Virtuals are in the virtual base list and already constructed.
1989 if (Base->isVirtual())
1990 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001991
Alexis Hunt1d792652011-01-08 20:30:50 +00001992 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001993 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1994 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001995 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001996 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001997 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001998 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001999 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002000 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002001 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002002 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002003
John McCallbc83b3f2010-05-20 23:23:51 +00002004 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002005 }
2006 }
Mike Stump11289f42009-09-09 15:08:12 +00002007
John McCallbc83b3f2010-05-20 23:23:51 +00002008 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002009 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002010 E = ClassDecl->field_end(); Field != E; ++Field) {
2011 if ((*Field)->getType()->isIncompleteArrayType()) {
2012 assert(ClassDecl->hasFlexibleArrayMember() &&
2013 "Incomplete array type is not valid");
2014 continue;
2015 }
John McCallbc83b3f2010-05-20 23:23:51 +00002016 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002017 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002018 }
Mike Stump11289f42009-09-09 15:08:12 +00002019
John McCallbc83b3f2010-05-20 23:23:51 +00002020 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002021 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002022 Constructor->setNumCtorInitializers(NumInitializers);
2023 CXXCtorInitializer **baseOrMemberInitializers =
2024 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002025 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002026 NumInitializers * sizeof(CXXCtorInitializer*));
2027 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002028
John McCalla6309952010-03-16 21:39:52 +00002029 // Constructors implicitly reference the base and member
2030 // destructors.
2031 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2032 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002033 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002034
2035 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002036}
2037
Eli Friedman952c15d2009-07-21 19:28:10 +00002038static void *GetKeyForTopLevelField(FieldDecl *Field) {
2039 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002040 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002041 if (RT->getDecl()->isAnonymousStructOrUnion())
2042 return static_cast<void *>(RT->getDecl());
2043 }
2044 return static_cast<void *>(Field);
2045}
2046
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002047static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002048 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002049}
2050
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002051static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002052 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002053 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002054 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002055
Eli Friedman952c15d2009-07-21 19:28:10 +00002056 // For fields injected into the class via declaration of an anonymous union,
2057 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002058 FieldDecl *Field = Member->getAnyMember();
2059
John McCall23eebd92010-04-10 09:28:51 +00002060 // If the field is a member of an anonymous struct or union, our key
2061 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002062 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002063 if (RD->isAnonymousStructOrUnion()) {
2064 while (true) {
2065 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2066 if (Parent->isAnonymousStructOrUnion())
2067 RD = Parent;
2068 else
2069 break;
2070 }
2071
Anders Carlsson83ac3122010-03-30 16:19:37 +00002072 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Anders Carlssona942dcd2010-03-30 15:39:27 +00002075 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002076}
2077
Anders Carlssone857b292010-04-02 03:37:03 +00002078static void
2079DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002080 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002081 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002082 unsigned NumInits) {
2083 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002084 return;
Mike Stump11289f42009-09-09 15:08:12 +00002085
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002086 // Don't check initializers order unless the warning is enabled at the
2087 // location of at least one initializer.
2088 bool ShouldCheckOrder = false;
2089 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002090 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002091 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2092 Init->getSourceLocation())
2093 != Diagnostic::Ignored) {
2094 ShouldCheckOrder = true;
2095 break;
2096 }
2097 }
2098 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002099 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002100
John McCallbb7b6582010-04-10 07:37:23 +00002101 // Build the list of bases and members in the order that they'll
2102 // actually be initialized. The explicit initializers should be in
2103 // this same order but may be missing things.
2104 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002105
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002106 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2107
John McCallbb7b6582010-04-10 07:37:23 +00002108 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002109 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002110 ClassDecl->vbases_begin(),
2111 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002112 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002113
John McCallbb7b6582010-04-10 07:37:23 +00002114 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002115 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002116 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002117 if (Base->isVirtual())
2118 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002119 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
John McCallbb7b6582010-04-10 07:37:23 +00002122 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002123 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2124 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002125 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002126
John McCallbb7b6582010-04-10 07:37:23 +00002127 unsigned NumIdealInits = IdealInitKeys.size();
2128 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002129
Alexis Hunt1d792652011-01-08 20:30:50 +00002130 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002131 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002132 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002133 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002134
2135 // Scan forward to try to find this initializer in the idealized
2136 // initializers list.
2137 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2138 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002139 break;
John McCallbb7b6582010-04-10 07:37:23 +00002140
2141 // If we didn't find this initializer, it must be because we
2142 // scanned past it on a previous iteration. That can only
2143 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002144 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002145 Sema::SemaDiagnosticBuilder D =
2146 SemaRef.Diag(PrevInit->getSourceLocation(),
2147 diag::warn_initializer_out_of_order);
2148
Francois Pichetd583da02010-12-04 09:14:42 +00002149 if (PrevInit->isAnyMemberInitializer())
2150 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002151 else
2152 D << 1 << PrevInit->getBaseClassInfo()->getType();
2153
Francois Pichetd583da02010-12-04 09:14:42 +00002154 if (Init->isAnyMemberInitializer())
2155 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002156 else
2157 D << 1 << Init->getBaseClassInfo()->getType();
2158
2159 // Move back to the initializer's location in the ideal list.
2160 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2161 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002162 break;
John McCallbb7b6582010-04-10 07:37:23 +00002163
2164 assert(IdealIndex != NumIdealInits &&
2165 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002166 }
John McCallbb7b6582010-04-10 07:37:23 +00002167
2168 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002169 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002170}
2171
John McCall23eebd92010-04-10 09:28:51 +00002172namespace {
2173bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002174 CXXCtorInitializer *Init,
2175 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002176 if (!PrevInit) {
2177 PrevInit = Init;
2178 return false;
2179 }
2180
2181 if (FieldDecl *Field = Init->getMember())
2182 S.Diag(Init->getSourceLocation(),
2183 diag::err_multiple_mem_initialization)
2184 << Field->getDeclName()
2185 << Init->getSourceRange();
2186 else {
John McCall424cec92011-01-19 06:33:43 +00002187 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002188 assert(BaseClass && "neither field nor base");
2189 S.Diag(Init->getSourceLocation(),
2190 diag::err_multiple_base_initialization)
2191 << QualType(BaseClass, 0)
2192 << Init->getSourceRange();
2193 }
2194 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2195 << 0 << PrevInit->getSourceRange();
2196
2197 return true;
2198}
2199
Alexis Hunt1d792652011-01-08 20:30:50 +00002200typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002201typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2202
2203bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002204 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002205 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002206 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002207 RecordDecl *Parent = Field->getParent();
2208 if (!Parent->isAnonymousStructOrUnion())
2209 return false;
2210
2211 NamedDecl *Child = Field;
2212 do {
2213 if (Parent->isUnion()) {
2214 UnionEntry &En = Unions[Parent];
2215 if (En.first && En.first != Child) {
2216 S.Diag(Init->getSourceLocation(),
2217 diag::err_multiple_mem_union_initialization)
2218 << Field->getDeclName()
2219 << Init->getSourceRange();
2220 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2221 << 0 << En.second->getSourceRange();
2222 return true;
2223 } else if (!En.first) {
2224 En.first = Child;
2225 En.second = Init;
2226 }
2227 }
2228
2229 Child = Parent;
2230 Parent = cast<RecordDecl>(Parent->getDeclContext());
2231 } while (Parent->isAnonymousStructOrUnion());
2232
2233 return false;
2234}
2235}
2236
Anders Carlssone857b292010-04-02 03:37:03 +00002237/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002238void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002239 SourceLocation ColonLoc,
2240 MemInitTy **meminits, unsigned NumMemInits,
2241 bool AnyErrors) {
2242 if (!ConstructorDecl)
2243 return;
2244
2245 AdjustDeclIfTemplate(ConstructorDecl);
2246
2247 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002248 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002249
2250 if (!Constructor) {
2251 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2252 return;
2253 }
2254
Alexis Hunt1d792652011-01-08 20:30:50 +00002255 CXXCtorInitializer **MemInits =
2256 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002257
2258 // Mapping for the duplicate initializers check.
2259 // For member initializers, this is keyed with a FieldDecl*.
2260 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002261 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002262
2263 // Mapping for the inconsistent anonymous-union initializers check.
2264 RedundantUnionMap MemberUnions;
2265
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002266 bool HadError = false;
2267 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002268 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002269
Abramo Bagnara341d7832010-05-26 18:09:23 +00002270 // Set the source order index.
2271 Init->setSourceOrder(i);
2272
Francois Pichetd583da02010-12-04 09:14:42 +00002273 if (Init->isAnyMemberInitializer()) {
2274 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002275 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2276 CheckRedundantUnionInit(*this, Init, MemberUnions))
2277 HadError = true;
2278 } else {
2279 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2280 if (CheckRedundantInit(*this, Init, Members[Key]))
2281 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002282 }
Anders Carlssone857b292010-04-02 03:37:03 +00002283 }
2284
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002285 if (HadError)
2286 return;
2287
Anders Carlssone857b292010-04-02 03:37:03 +00002288 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002289
Alexis Hunt1d792652011-01-08 20:30:50 +00002290 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002291}
2292
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002293void
John McCalla6309952010-03-16 21:39:52 +00002294Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2295 CXXRecordDecl *ClassDecl) {
2296 // Ignore dependent contexts.
2297 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002298 return;
John McCall1064d7e2010-03-16 05:22:47 +00002299
2300 // FIXME: all the access-control diagnostics are positioned on the
2301 // field/base declaration. That's probably good; that said, the
2302 // user might reasonably want to know why the destructor is being
2303 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002304
Anders Carlssondee9a302009-11-17 04:44:12 +00002305 // Non-static data members.
2306 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2307 E = ClassDecl->field_end(); I != E; ++I) {
2308 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002309 if (Field->isInvalidDecl())
2310 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002311 QualType FieldType = Context.getBaseElementType(Field->getType());
2312
2313 const RecordType* RT = FieldType->getAs<RecordType>();
2314 if (!RT)
2315 continue;
2316
2317 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2318 if (FieldClassDecl->hasTrivialDestructor())
2319 continue;
2320
Douglas Gregore71edda2010-07-01 22:47:18 +00002321 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002322 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002323 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002324 << Field->getDeclName()
2325 << FieldType);
2326
John McCalla6309952010-03-16 21:39:52 +00002327 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002328 }
2329
John McCall1064d7e2010-03-16 05:22:47 +00002330 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2331
Anders Carlssondee9a302009-11-17 04:44:12 +00002332 // Bases.
2333 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2334 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002335 // Bases are always records in a well-formed non-dependent class.
2336 const RecordType *RT = Base->getType()->getAs<RecordType>();
2337
2338 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002339 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002340 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002341
2342 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002344 if (BaseClassDecl->hasTrivialDestructor())
2345 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002346
Douglas Gregore71edda2010-07-01 22:47:18 +00002347 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002348
2349 // FIXME: caret should be on the start of the class name
2350 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002351 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002352 << Base->getType()
2353 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002354
John McCalla6309952010-03-16 21:39:52 +00002355 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002356 }
2357
2358 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002359 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2360 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002361
2362 // Bases are always records in a well-formed non-dependent class.
2363 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2364
2365 // Ignore direct virtual bases.
2366 if (DirectVirtualBases.count(RT))
2367 continue;
2368
Anders Carlssondee9a302009-11-17 04:44:12 +00002369 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002370 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002371 if (BaseClassDecl->hasTrivialDestructor())
2372 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002373
Douglas Gregore71edda2010-07-01 22:47:18 +00002374 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002375 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002376 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002377 << VBase->getType());
2378
John McCalla6309952010-03-16 21:39:52 +00002379 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002380 }
2381}
2382
John McCall48871652010-08-21 09:40:31 +00002383void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002384 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002385 return;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Mike Stump11289f42009-09-09 15:08:12 +00002387 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002388 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002389 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002390}
2391
Mike Stump11289f42009-09-09 15:08:12 +00002392bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002393 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002394 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002395 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002396 else
John McCall02db245d2010-08-18 09:41:07 +00002397 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002398}
2399
Anders Carlssoneabf7702009-08-27 00:13:57 +00002400bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002401 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002402 if (!getLangOptions().CPlusPlus)
2403 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002404
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002405 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002406 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002407
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002408 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002409 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002410 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002411 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002413 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002414 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002417 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002418 if (!RT)
2419 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002420
John McCall67da35c2010-02-04 22:26:26 +00002421 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002422
John McCall02db245d2010-08-18 09:41:07 +00002423 // We can't answer whether something is abstract until it has a
2424 // definition. If it's currently being defined, we'll walk back
2425 // over all the declarations when we have a full definition.
2426 const CXXRecordDecl *Def = RD->getDefinition();
2427 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002428 return false;
2429
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002430 if (!RD->isAbstract())
2431 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002432
Anders Carlssoneabf7702009-08-27 00:13:57 +00002433 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002434 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002435
John McCall02db245d2010-08-18 09:41:07 +00002436 return true;
2437}
2438
2439void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2440 // Check if we've already emitted the list of pure virtual functions
2441 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002442 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002443 return;
Mike Stump11289f42009-09-09 15:08:12 +00002444
Douglas Gregor4165bd62010-03-23 23:47:56 +00002445 CXXFinalOverriderMap FinalOverriders;
2446 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002447
Anders Carlssona2f74f32010-06-03 01:00:02 +00002448 // Keep a set of seen pure methods so we won't diagnose the same method
2449 // more than once.
2450 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2451
Douglas Gregor4165bd62010-03-23 23:47:56 +00002452 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2453 MEnd = FinalOverriders.end();
2454 M != MEnd;
2455 ++M) {
2456 for (OverridingMethods::iterator SO = M->second.begin(),
2457 SOEnd = M->second.end();
2458 SO != SOEnd; ++SO) {
2459 // C++ [class.abstract]p4:
2460 // A class is abstract if it contains or inherits at least one
2461 // pure virtual function for which the final overrider is pure
2462 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002463
Douglas Gregor4165bd62010-03-23 23:47:56 +00002464 //
2465 if (SO->second.size() != 1)
2466 continue;
2467
2468 if (!SO->second.front().Method->isPure())
2469 continue;
2470
Anders Carlssona2f74f32010-06-03 01:00:02 +00002471 if (!SeenPureMethods.insert(SO->second.front().Method))
2472 continue;
2473
Douglas Gregor4165bd62010-03-23 23:47:56 +00002474 Diag(SO->second.front().Method->getLocation(),
2475 diag::note_pure_virtual_function)
2476 << SO->second.front().Method->getDeclName();
2477 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002478 }
2479
2480 if (!PureVirtualClassDiagSet)
2481 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2482 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002483}
2484
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002485namespace {
John McCall02db245d2010-08-18 09:41:07 +00002486struct AbstractUsageInfo {
2487 Sema &S;
2488 CXXRecordDecl *Record;
2489 CanQualType AbstractType;
2490 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002491
John McCall02db245d2010-08-18 09:41:07 +00002492 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2493 : S(S), Record(Record),
2494 AbstractType(S.Context.getCanonicalType(
2495 S.Context.getTypeDeclType(Record))),
2496 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002497
John McCall02db245d2010-08-18 09:41:07 +00002498 void DiagnoseAbstractType() {
2499 if (Invalid) return;
2500 S.DiagnoseAbstractType(Record);
2501 Invalid = true;
2502 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002503
John McCall02db245d2010-08-18 09:41:07 +00002504 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2505};
2506
2507struct CheckAbstractUsage {
2508 AbstractUsageInfo &Info;
2509 const NamedDecl *Ctx;
2510
2511 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2512 : Info(Info), Ctx(Ctx) {}
2513
2514 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2515 switch (TL.getTypeLocClass()) {
2516#define ABSTRACT_TYPELOC(CLASS, PARENT)
2517#define TYPELOC(CLASS, PARENT) \
2518 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2519#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002520 }
John McCall02db245d2010-08-18 09:41:07 +00002521 }
Mike Stump11289f42009-09-09 15:08:12 +00002522
John McCall02db245d2010-08-18 09:41:07 +00002523 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2524 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2525 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2526 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2527 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002528 }
John McCall02db245d2010-08-18 09:41:07 +00002529 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002530
John McCall02db245d2010-08-18 09:41:07 +00002531 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2532 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2533 }
Mike Stump11289f42009-09-09 15:08:12 +00002534
John McCall02db245d2010-08-18 09:41:07 +00002535 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2536 // Visit the type parameters from a permissive context.
2537 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2538 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2539 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2540 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2541 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2542 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002543 }
John McCall02db245d2010-08-18 09:41:07 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
John McCall02db245d2010-08-18 09:41:07 +00002546 // Visit pointee types from a permissive context.
2547#define CheckPolymorphic(Type) \
2548 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2549 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2550 }
2551 CheckPolymorphic(PointerTypeLoc)
2552 CheckPolymorphic(ReferenceTypeLoc)
2553 CheckPolymorphic(MemberPointerTypeLoc)
2554 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002555
John McCall02db245d2010-08-18 09:41:07 +00002556 /// Handle all the types we haven't given a more specific
2557 /// implementation for above.
2558 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2559 // Every other kind of type that we haven't called out already
2560 // that has an inner type is either (1) sugar or (2) contains that
2561 // inner type in some way as a subobject.
2562 if (TypeLoc Next = TL.getNextTypeLoc())
2563 return Visit(Next, Sel);
2564
2565 // If there's no inner type and we're in a permissive context,
2566 // don't diagnose.
2567 if (Sel == Sema::AbstractNone) return;
2568
2569 // Check whether the type matches the abstract type.
2570 QualType T = TL.getType();
2571 if (T->isArrayType()) {
2572 Sel = Sema::AbstractArrayType;
2573 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002574 }
John McCall02db245d2010-08-18 09:41:07 +00002575 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2576 if (CT != Info.AbstractType) return;
2577
2578 // It matched; do some magic.
2579 if (Sel == Sema::AbstractArrayType) {
2580 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2581 << T << TL.getSourceRange();
2582 } else {
2583 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2584 << Sel << T << TL.getSourceRange();
2585 }
2586 Info.DiagnoseAbstractType();
2587 }
2588};
2589
2590void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2591 Sema::AbstractDiagSelID Sel) {
2592 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2593}
2594
2595}
2596
2597/// Check for invalid uses of an abstract type in a method declaration.
2598static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2599 CXXMethodDecl *MD) {
2600 // No need to do the check on definitions, which require that
2601 // the return/param types be complete.
2602 if (MD->isThisDeclarationADefinition())
2603 return;
2604
2605 // For safety's sake, just ignore it if we don't have type source
2606 // information. This should never happen for non-implicit methods,
2607 // but...
2608 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2609 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2610}
2611
2612/// Check for invalid uses of an abstract type within a class definition.
2613static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2614 CXXRecordDecl *RD) {
2615 for (CXXRecordDecl::decl_iterator
2616 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2617 Decl *D = *I;
2618 if (D->isImplicit()) continue;
2619
2620 // Methods and method templates.
2621 if (isa<CXXMethodDecl>(D)) {
2622 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2623 } else if (isa<FunctionTemplateDecl>(D)) {
2624 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2625 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2626
2627 // Fields and static variables.
2628 } else if (isa<FieldDecl>(D)) {
2629 FieldDecl *FD = cast<FieldDecl>(D);
2630 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2631 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2632 } else if (isa<VarDecl>(D)) {
2633 VarDecl *VD = cast<VarDecl>(D);
2634 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2635 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2636
2637 // Nested classes and class templates.
2638 } else if (isa<CXXRecordDecl>(D)) {
2639 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2640 } else if (isa<ClassTemplateDecl>(D)) {
2641 CheckAbstractClassUsage(Info,
2642 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2643 }
2644 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002645}
2646
Douglas Gregorc99f1552009-12-03 18:33:45 +00002647/// \brief Perform semantic checks on a class definition that has been
2648/// completing, introducing implicitly-declared members, checking for
2649/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002650void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002651 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002652 return;
2653
John McCall02db245d2010-08-18 09:41:07 +00002654 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2655 AbstractUsageInfo Info(*this, Record);
2656 CheckAbstractClassUsage(Info, Record);
2657 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002658
2659 // If this is not an aggregate type and has no user-declared constructor,
2660 // complain about any non-static data members of reference or const scalar
2661 // type, since they will never get initializers.
2662 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2663 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2664 bool Complained = false;
2665 for (RecordDecl::field_iterator F = Record->field_begin(),
2666 FEnd = Record->field_end();
2667 F != FEnd; ++F) {
2668 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002669 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002670 if (!Complained) {
2671 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2672 << Record->getTagKind() << Record;
2673 Complained = true;
2674 }
2675
2676 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2677 << F->getType()->isReferenceType()
2678 << F->getDeclName();
2679 }
2680 }
2681 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002682
2683 if (Record->isDynamicClass())
2684 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002685
2686 if (Record->getIdentifier()) {
2687 // C++ [class.mem]p13:
2688 // If T is the name of a class, then each of the following shall have a
2689 // name different from T:
2690 // - every member of every anonymous union that is a member of class T.
2691 //
2692 // C++ [class.mem]p14:
2693 // In addition, if class T has a user-declared constructor (12.1), every
2694 // non-static data member of class T shall have a name different from T.
2695 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002696 R.first != R.second; ++R.first) {
2697 NamedDecl *D = *R.first;
2698 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2699 isa<IndirectFieldDecl>(D)) {
2700 Diag(D->getLocation(), diag::err_member_name_of_class)
2701 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002702 break;
2703 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002704 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002705 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002706}
2707
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002708void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002709 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002710 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002711 SourceLocation RBrac,
2712 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002713 if (!TagDecl)
2714 return;
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002716 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002717
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002718 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002719 // strict aliasing violation!
2720 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002721 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002722
Douglas Gregor0be31a22010-07-02 17:43:08 +00002723 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002724 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002725}
2726
Douglas Gregor95755162010-07-01 05:10:53 +00002727namespace {
2728 /// \brief Helper class that collects exception specifications for
2729 /// implicitly-declared special member functions.
2730 class ImplicitExceptionSpecification {
2731 ASTContext &Context;
2732 bool AllowsAllExceptions;
2733 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2734 llvm::SmallVector<QualType, 4> Exceptions;
2735
2736 public:
2737 explicit ImplicitExceptionSpecification(ASTContext &Context)
2738 : Context(Context), AllowsAllExceptions(false) { }
2739
2740 /// \brief Whether the special member function should have any
2741 /// exception specification at all.
2742 bool hasExceptionSpecification() const {
2743 return !AllowsAllExceptions;
2744 }
2745
2746 /// \brief Whether the special member function should have a
2747 /// throw(...) exception specification (a Microsoft extension).
2748 bool hasAnyExceptionSpecification() const {
2749 return false;
2750 }
2751
2752 /// \brief The number of exceptions in the exception specification.
2753 unsigned size() const { return Exceptions.size(); }
2754
2755 /// \brief The set of exceptions in the exception specification.
2756 const QualType *data() const { return Exceptions.data(); }
2757
2758 /// \brief Note that
2759 void CalledDecl(CXXMethodDecl *Method) {
2760 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002761 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002762 return;
2763
2764 const FunctionProtoType *Proto
2765 = Method->getType()->getAs<FunctionProtoType>();
2766
2767 // If this function can throw any exceptions, make a note of that.
2768 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2769 AllowsAllExceptions = true;
2770 ExceptionsSeen.clear();
2771 Exceptions.clear();
2772 return;
2773 }
2774
2775 // Record the exceptions in this function's exception specification.
2776 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2777 EEnd = Proto->exception_end();
2778 E != EEnd; ++E)
2779 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2780 Exceptions.push_back(*E);
2781 }
2782 };
2783}
2784
2785
Douglas Gregor05379422008-11-03 17:51:48 +00002786/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2787/// special functions, such as the default constructor, copy
2788/// constructor, or destructor, to the given C++ class (C++
2789/// [special]p1). This routine can only be executed just before the
2790/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002791void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002792 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002793 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002794
Douglas Gregor54be3392010-07-01 17:57:27 +00002795 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002796 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002797
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002798 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2799 ++ASTContext::NumImplicitCopyAssignmentOperators;
2800
2801 // If we have a dynamic class, then the copy assignment operator may be
2802 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2803 // it shows up in the right place in the vtable and that we diagnose
2804 // problems with the implicit exception specification.
2805 if (ClassDecl->isDynamicClass())
2806 DeclareImplicitCopyAssignment(ClassDecl);
2807 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002808
Douglas Gregor7454c562010-07-02 20:37:36 +00002809 if (!ClassDecl->hasUserDeclaredDestructor()) {
2810 ++ASTContext::NumImplicitDestructors;
2811
2812 // If we have a dynamic class, then the destructor may be virtual, so we
2813 // have to declare the destructor immediately. This ensures that, e.g., it
2814 // shows up in the right place in the vtable and that we diagnose problems
2815 // with the implicit exception specification.
2816 if (ClassDecl->isDynamicClass())
2817 DeclareImplicitDestructor(ClassDecl);
2818 }
Douglas Gregor05379422008-11-03 17:51:48 +00002819}
2820
John McCall48871652010-08-21 09:40:31 +00002821void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002822 if (!D)
2823 return;
2824
2825 TemplateParameterList *Params = 0;
2826 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2827 Params = Template->getTemplateParameters();
2828 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2829 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2830 Params = PartialSpec->getTemplateParameters();
2831 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002832 return;
2833
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002834 for (TemplateParameterList::iterator Param = Params->begin(),
2835 ParamEnd = Params->end();
2836 Param != ParamEnd; ++Param) {
2837 NamedDecl *Named = cast<NamedDecl>(*Param);
2838 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002839 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002840 IdResolver.AddDecl(Named);
2841 }
2842 }
2843}
2844
John McCall48871652010-08-21 09:40:31 +00002845void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002846 if (!RecordD) return;
2847 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002848 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002849 PushDeclContext(S, Record);
2850}
2851
John McCall48871652010-08-21 09:40:31 +00002852void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002853 if (!RecordD) return;
2854 PopDeclContext();
2855}
2856
Douglas Gregor4d87df52008-12-16 21:30:33 +00002857/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2858/// parsing a top-level (non-nested) C++ class, and we are now
2859/// parsing those parts of the given Method declaration that could
2860/// not be parsed earlier (C++ [class.mem]p2), such as default
2861/// arguments. This action should enter the scope of the given
2862/// Method declaration as if we had just parsed the qualified method
2863/// name. However, it should not bring the parameters into scope;
2864/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002865void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002866}
2867
2868/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2869/// C++ method declaration. We're (re-)introducing the given
2870/// function parameter into scope for use in parsing later parts of
2871/// the method declaration. For example, we could see an
2872/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002873void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002874 if (!ParamD)
2875 return;
Mike Stump11289f42009-09-09 15:08:12 +00002876
John McCall48871652010-08-21 09:40:31 +00002877 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002878
2879 // If this parameter has an unparsed default argument, clear it out
2880 // to make way for the parsed default argument.
2881 if (Param->hasUnparsedDefaultArg())
2882 Param->setDefaultArg(0);
2883
John McCall48871652010-08-21 09:40:31 +00002884 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002885 if (Param->getDeclName())
2886 IdResolver.AddDecl(Param);
2887}
2888
2889/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2890/// processing the delayed method declaration for Method. The method
2891/// declaration is now considered finished. There may be a separate
2892/// ActOnStartOfFunctionDef action later (not necessarily
2893/// immediately!) for this method, if it was also defined inside the
2894/// class body.
John McCall48871652010-08-21 09:40:31 +00002895void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002896 if (!MethodD)
2897 return;
Mike Stump11289f42009-09-09 15:08:12 +00002898
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002899 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002900
John McCall48871652010-08-21 09:40:31 +00002901 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002902
2903 // Now that we have our default arguments, check the constructor
2904 // again. It could produce additional diagnostics or affect whether
2905 // the class has implicitly-declared destructors, among other
2906 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002907 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2908 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002909
2910 // Check the default arguments, which we may have added.
2911 if (!Method->isInvalidDecl())
2912 CheckCXXDefaultArguments(Method);
2913}
2914
Douglas Gregor831c93f2008-11-05 20:51:48 +00002915/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002916/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002917/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002918/// emit diagnostics and set the invalid bit to true. In any case, the type
2919/// will be updated to reflect a well-formed type for the constructor and
2920/// returned.
2921QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002922 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002923 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002924
2925 // C++ [class.ctor]p3:
2926 // A constructor shall not be virtual (10.3) or static (9.4). A
2927 // constructor can be invoked for a const, volatile or const
2928 // volatile object. A constructor shall not be declared const,
2929 // volatile, or const volatile (9.3.2).
2930 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002931 if (!D.isInvalidType())
2932 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2933 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2934 << SourceRange(D.getIdentifierLoc());
2935 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002936 }
John McCall8e7d6562010-08-26 03:08:43 +00002937 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002938 if (!D.isInvalidType())
2939 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2940 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2941 << SourceRange(D.getIdentifierLoc());
2942 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002943 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002944 }
Mike Stump11289f42009-09-09 15:08:12 +00002945
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002946 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002947 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002948 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002949 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2950 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002951 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002952 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2953 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002954 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002955 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2956 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002957 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002958 }
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregor831c93f2008-11-05 20:51:48 +00002960 // Rebuild the function type "R" without any type qualifiers (in
2961 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002962 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002963 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002964 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2965 return R;
2966
2967 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2968 EPI.TypeQuals = 0;
2969
Chris Lattner38378bf2009-04-25 08:28:21 +00002970 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002971 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002972}
2973
Douglas Gregor4d87df52008-12-16 21:30:33 +00002974/// CheckConstructor - Checks a fully-formed constructor for
2975/// well-formedness, issuing any diagnostics required. Returns true if
2976/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002977void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002978 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002979 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2980 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002981 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002982
2983 // C++ [class.copy]p3:
2984 // A declaration of a constructor for a class X is ill-formed if
2985 // its first parameter is of type (optionally cv-qualified) X and
2986 // either there are no other parameters or else all other
2987 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002988 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002989 ((Constructor->getNumParams() == 1) ||
2990 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002991 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2992 Constructor->getTemplateSpecializationKind()
2993 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002994 QualType ParamType = Constructor->getParamDecl(0)->getType();
2995 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2996 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002997 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002998 const char *ConstRef
2999 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3000 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003001 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003002 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003003
3004 // FIXME: Rather that making the constructor invalid, we should endeavor
3005 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003006 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003007 }
3008 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003009}
3010
John McCalldeb646e2010-08-04 01:04:25 +00003011/// CheckDestructor - Checks a fully-formed destructor definition for
3012/// well-formedness, issuing any diagnostics required. Returns true
3013/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003014bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003015 CXXRecordDecl *RD = Destructor->getParent();
3016
3017 if (Destructor->isVirtual()) {
3018 SourceLocation Loc;
3019
3020 if (!Destructor->isImplicit())
3021 Loc = Destructor->getLocation();
3022 else
3023 Loc = RD->getLocation();
3024
3025 // If we have a virtual destructor, look up the deallocation function
3026 FunctionDecl *OperatorDelete = 0;
3027 DeclarationName Name =
3028 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003029 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003030 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003031
3032 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003033
3034 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003035 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003036
3037 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003038}
3039
Mike Stump11289f42009-09-09 15:08:12 +00003040static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003041FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3042 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3043 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003044 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003045}
3046
Douglas Gregor831c93f2008-11-05 20:51:48 +00003047/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3048/// the well-formednes of the destructor declarator @p D with type @p
3049/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003050/// emit diagnostics and set the declarator to invalid. Even if this happens,
3051/// will be updated to reflect a well-formed type for the destructor and
3052/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003053QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003054 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003055 // C++ [class.dtor]p1:
3056 // [...] A typedef-name that names a class is a class-name
3057 // (7.1.3); however, a typedef-name that names a class shall not
3058 // be used as the identifier in the declarator for a destructor
3059 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003060 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003061 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003062 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003063 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003064
3065 // C++ [class.dtor]p2:
3066 // A destructor is used to destroy objects of its class type. A
3067 // destructor takes no parameters, and no return type can be
3068 // specified for it (not even void). The address of a destructor
3069 // shall not be taken. A destructor shall not be static. A
3070 // destructor can be invoked for a const, volatile or const
3071 // volatile object. A destructor shall not be declared const,
3072 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003073 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003074 if (!D.isInvalidType())
3075 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3076 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003077 << SourceRange(D.getIdentifierLoc())
3078 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3079
John McCall8e7d6562010-08-26 03:08:43 +00003080 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003081 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003082 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003083 // Destructors don't have return types, but the parser will
3084 // happily parse something like:
3085 //
3086 // class X {
3087 // float ~X();
3088 // };
3089 //
3090 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003091 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3092 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3093 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003096 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003097 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003098 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003099 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3100 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003101 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003102 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3103 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003104 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003105 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3106 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003107 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003108 }
3109
3110 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003111 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003112 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3113
3114 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003115 FTI.freeArgs();
3116 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003117 }
3118
Mike Stump11289f42009-09-09 15:08:12 +00003119 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003120 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003121 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003122 D.setInvalidType();
3123 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003124
3125 // Rebuild the function type "R" without any type qualifiers or
3126 // parameters (in case any of the errors above fired) and with
3127 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003128 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003129 if (!D.isInvalidType())
3130 return R;
3131
Douglas Gregor95755162010-07-01 05:10:53 +00003132 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003133 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3134 EPI.Variadic = false;
3135 EPI.TypeQuals = 0;
3136 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003137}
3138
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003139/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3140/// well-formednes of the conversion function declarator @p D with
3141/// type @p R. If there are any errors in the declarator, this routine
3142/// will emit diagnostics and return true. Otherwise, it will return
3143/// false. Either way, the type @p R will be updated to reflect a
3144/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003145void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003146 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003147 // C++ [class.conv.fct]p1:
3148 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003149 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003150 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003151 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003152 if (!D.isInvalidType())
3153 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3154 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3155 << SourceRange(D.getIdentifierLoc());
3156 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003157 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003158 }
John McCall212fa2e2010-04-13 00:04:31 +00003159
3160 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3161
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003162 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003163 // Conversion functions don't have return types, but the parser will
3164 // happily parse something like:
3165 //
3166 // class X {
3167 // float operator bool();
3168 // };
3169 //
3170 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003171 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3172 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3173 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003174 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003175 }
3176
John McCall212fa2e2010-04-13 00:04:31 +00003177 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3178
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003179 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003180 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003181 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3182
3183 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003184 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003185 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003186 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003187 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003188 D.setInvalidType();
3189 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003190
John McCall212fa2e2010-04-13 00:04:31 +00003191 // Diagnose "&operator bool()" and other such nonsense. This
3192 // is actually a gcc extension which we don't support.
3193 if (Proto->getResultType() != ConvType) {
3194 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3195 << Proto->getResultType();
3196 D.setInvalidType();
3197 ConvType = Proto->getResultType();
3198 }
3199
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003200 // C++ [class.conv.fct]p4:
3201 // The conversion-type-id shall not represent a function type nor
3202 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003203 if (ConvType->isArrayType()) {
3204 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3205 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003206 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003207 } else if (ConvType->isFunctionType()) {
3208 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3209 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003210 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003211 }
3212
3213 // Rebuild the function type "R" without any parameters (in case any
3214 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003215 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003216 if (D.isInvalidType())
3217 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003218
Douglas Gregor5fb53972009-01-14 15:45:31 +00003219 // C++0x explicit conversion operators.
3220 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003221 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003222 diag::warn_explicit_conversion_functions)
3223 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003224}
3225
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003226/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3227/// the declaration of the given C++ conversion function. This routine
3228/// is responsible for recording the conversion function in the C++
3229/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003230Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003231 assert(Conversion && "Expected to receive a conversion function declaration");
3232
Douglas Gregor4287b372008-12-12 08:25:50 +00003233 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003234
3235 // Make sure we aren't redeclaring the conversion function.
3236 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003237
3238 // C++ [class.conv.fct]p1:
3239 // [...] A conversion function is never used to convert a
3240 // (possibly cv-qualified) object to the (possibly cv-qualified)
3241 // same object type (or a reference to it), to a (possibly
3242 // cv-qualified) base class of that type (or a reference to it),
3243 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003244 // FIXME: Suppress this warning if the conversion function ends up being a
3245 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003246 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003247 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003248 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003249 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003250 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3251 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003252 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003253 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003254 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3255 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003256 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003257 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003258 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003259 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003260 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003261 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003262 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003263 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003264 }
3265
Douglas Gregor457104e2010-09-29 04:25:11 +00003266 if (FunctionTemplateDecl *ConversionTemplate
3267 = Conversion->getDescribedFunctionTemplate())
3268 return ConversionTemplate;
3269
John McCall48871652010-08-21 09:40:31 +00003270 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003271}
3272
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003273//===----------------------------------------------------------------------===//
3274// Namespace Handling
3275//===----------------------------------------------------------------------===//
3276
John McCallb1be5232010-08-26 09:15:37 +00003277
3278
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003279/// ActOnStartNamespaceDef - This is called at the start of a namespace
3280/// definition.
John McCall48871652010-08-21 09:40:31 +00003281Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003282 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003283 SourceLocation IdentLoc,
3284 IdentifierInfo *II,
3285 SourceLocation LBrace,
3286 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003287 // anonymous namespace starts at its left brace
3288 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3289 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003290 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003291 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003292
3293 Scope *DeclRegionScope = NamespcScope->getParent();
3294
Anders Carlssona7bcade2010-02-07 01:09:23 +00003295 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3296
John McCall2faf32c2010-12-10 02:59:44 +00003297 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3298 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003299
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003300 if (II) {
3301 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003302 // The identifier in an original-namespace-definition shall not
3303 // have been previously defined in the declarative region in
3304 // which the original-namespace-definition appears. The
3305 // identifier in an original-namespace-definition is the name of
3306 // the namespace. Subsequently in that declarative region, it is
3307 // treated as an original-namespace-name.
3308 //
3309 // Since namespace names are unique in their scope, and we don't
3310 // look through using directives, just
3311 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3312 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003313
Douglas Gregor91f84212008-12-11 16:49:14 +00003314 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3315 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003316 if (Namespc->isInline() != OrigNS->isInline()) {
3317 // inline-ness must match
3318 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3319 << Namespc->isInline();
3320 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3321 Namespc->setInvalidDecl();
3322 // Recover by ignoring the new namespace's inline status.
3323 Namespc->setInline(OrigNS->isInline());
3324 }
3325
Douglas Gregor91f84212008-12-11 16:49:14 +00003326 // Attach this namespace decl to the chain of extended namespace
3327 // definitions.
3328 OrigNS->setNextNamespace(Namespc);
3329 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003330
Mike Stump11289f42009-09-09 15:08:12 +00003331 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003332 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003333 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003334 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003335 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003336 } else if (PrevDecl) {
3337 // This is an invalid name redefinition.
3338 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3339 << Namespc->getDeclName();
3340 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3341 Namespc->setInvalidDecl();
3342 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003343 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003344 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003345 // This is the first "real" definition of the namespace "std", so update
3346 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003347 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003348 // We had already defined a dummy namespace "std". Link this new
3349 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003350 StdNS->setNextNamespace(Namespc);
3351 StdNS->setLocation(IdentLoc);
3352 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003353 }
3354
3355 // Make our StdNamespace cache point at the first real definition of the
3356 // "std" namespace.
3357 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003358 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003359
3360 PushOnScopeChains(Namespc, DeclRegionScope);
3361 } else {
John McCall4fa53422009-10-01 00:25:31 +00003362 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003363 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003364
3365 // Link the anonymous namespace into its parent.
3366 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003367 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003368 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3369 PrevDecl = TU->getAnonymousNamespace();
3370 TU->setAnonymousNamespace(Namespc);
3371 } else {
3372 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3373 PrevDecl = ND->getAnonymousNamespace();
3374 ND->setAnonymousNamespace(Namespc);
3375 }
3376
3377 // Link the anonymous namespace with its previous declaration.
3378 if (PrevDecl) {
3379 assert(PrevDecl->isAnonymousNamespace());
3380 assert(!PrevDecl->getNextNamespace());
3381 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3382 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003383
3384 if (Namespc->isInline() != PrevDecl->isInline()) {
3385 // inline-ness must match
3386 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3387 << Namespc->isInline();
3388 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3389 Namespc->setInvalidDecl();
3390 // Recover by ignoring the new namespace's inline status.
3391 Namespc->setInline(PrevDecl->isInline());
3392 }
John McCall0db42252009-12-16 02:06:49 +00003393 }
John McCall4fa53422009-10-01 00:25:31 +00003394
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003395 CurContext->addDecl(Namespc);
3396
John McCall4fa53422009-10-01 00:25:31 +00003397 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3398 // behaves as if it were replaced by
3399 // namespace unique { /* empty body */ }
3400 // using namespace unique;
3401 // namespace unique { namespace-body }
3402 // where all occurrences of 'unique' in a translation unit are
3403 // replaced by the same identifier and this identifier differs
3404 // from all other identifiers in the entire program.
3405
3406 // We just create the namespace with an empty name and then add an
3407 // implicit using declaration, just like the standard suggests.
3408 //
3409 // CodeGen enforces the "universally unique" aspect by giving all
3410 // declarations semantically contained within an anonymous
3411 // namespace internal linkage.
3412
John McCall0db42252009-12-16 02:06:49 +00003413 if (!PrevDecl) {
3414 UsingDirectiveDecl* UD
3415 = UsingDirectiveDecl::Create(Context, CurContext,
3416 /* 'using' */ LBrace,
3417 /* 'namespace' */ SourceLocation(),
3418 /* qualifier */ SourceRange(),
3419 /* NNS */ NULL,
3420 /* identifier */ SourceLocation(),
3421 Namespc,
3422 /* Ancestor */ CurContext);
3423 UD->setImplicit();
3424 CurContext->addDecl(UD);
3425 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003426 }
3427
3428 // Although we could have an invalid decl (i.e. the namespace name is a
3429 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003430 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3431 // for the namespace has the declarations that showed up in that particular
3432 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003433 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003434 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003435}
3436
Sebastian Redla6602e92009-11-23 15:34:23 +00003437/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3438/// is a namespace alias, returns the namespace it points to.
3439static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3440 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3441 return AD->getNamespace();
3442 return dyn_cast_or_null<NamespaceDecl>(D);
3443}
3444
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003445/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3446/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003447void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003448 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3449 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3450 Namespc->setRBracLoc(RBrace);
3451 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003452 if (Namespc->hasAttr<VisibilityAttr>())
3453 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003454}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003455
John McCall28a0cf72010-08-25 07:42:41 +00003456CXXRecordDecl *Sema::getStdBadAlloc() const {
3457 return cast_or_null<CXXRecordDecl>(
3458 StdBadAlloc.get(Context.getExternalSource()));
3459}
3460
3461NamespaceDecl *Sema::getStdNamespace() const {
3462 return cast_or_null<NamespaceDecl>(
3463 StdNamespace.get(Context.getExternalSource()));
3464}
3465
Douglas Gregorcdf87022010-06-29 17:53:46 +00003466/// \brief Retrieve the special "std" namespace, which may require us to
3467/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003468NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003469 if (!StdNamespace) {
3470 // The "std" namespace has not yet been defined, so build one implicitly.
3471 StdNamespace = NamespaceDecl::Create(Context,
3472 Context.getTranslationUnitDecl(),
3473 SourceLocation(),
3474 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003475 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003476 }
3477
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003478 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003479}
3480
John McCall48871652010-08-21 09:40:31 +00003481Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003482 SourceLocation UsingLoc,
3483 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003484 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003485 SourceLocation IdentLoc,
3486 IdentifierInfo *NamespcName,
3487 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003488 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3489 assert(NamespcName && "Invalid NamespcName.");
3490 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003491
3492 // This can only happen along a recovery path.
3493 while (S->getFlags() & Scope::TemplateParamScope)
3494 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003495 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003496
Douglas Gregor889ceb72009-02-03 19:21:40 +00003497 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003498 NestedNameSpecifier *Qualifier = 0;
3499 if (SS.isSet())
3500 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3501
Douglas Gregor34074322009-01-14 22:20:51 +00003502 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003503 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3504 LookupParsedName(R, S, &SS);
3505 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003506 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003507
Douglas Gregorcdf87022010-06-29 17:53:46 +00003508 if (R.empty()) {
3509 // Allow "using namespace std;" or "using namespace ::std;" even if
3510 // "std" hasn't been defined yet, for GCC compatibility.
3511 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3512 NamespcName->isStr("std")) {
3513 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003514 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003515 R.resolveKind();
3516 }
3517 // Otherwise, attempt typo correction.
3518 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3519 CTC_NoKeywords, 0)) {
3520 if (R.getAsSingle<NamespaceDecl>() ||
3521 R.getAsSingle<NamespaceAliasDecl>()) {
3522 if (DeclContext *DC = computeDeclContext(SS, false))
3523 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3524 << NamespcName << DC << Corrected << SS.getRange()
3525 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3526 else
3527 Diag(IdentLoc, diag::err_using_directive_suggest)
3528 << NamespcName << Corrected
3529 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3530 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3531 << Corrected;
3532
3533 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003534 } else {
3535 R.clear();
3536 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003537 }
3538 }
3539 }
3540
John McCall9f3059a2009-10-09 21:13:30 +00003541 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003542 NamedDecl *Named = R.getFoundDecl();
3543 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3544 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003545 // C++ [namespace.udir]p1:
3546 // A using-directive specifies that the names in the nominated
3547 // namespace can be used in the scope in which the
3548 // using-directive appears after the using-directive. During
3549 // unqualified name lookup (3.4.1), the names appear as if they
3550 // were declared in the nearest enclosing namespace which
3551 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003552 // namespace. [Note: in this context, "contains" means "contains
3553 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003554
3555 // Find enclosing context containing both using-directive and
3556 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003557 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003558 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3559 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3560 CommonAncestor = CommonAncestor->getParent();
3561
Sebastian Redla6602e92009-11-23 15:34:23 +00003562 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003563 SS.getRange(),
3564 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003565 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003566 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003567 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003568 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003569 }
3570
Douglas Gregor889ceb72009-02-03 19:21:40 +00003571 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003572 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003573}
3574
3575void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3576 // If scope has associated entity, then using directive is at namespace
3577 // or translation unit scope. We add UsingDirectiveDecls, into
3578 // it's lookup structure.
3579 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003580 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003581 else
3582 // Otherwise it is block-sope. using-directives will affect lookup
3583 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003584 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003585}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003586
Douglas Gregorfec52632009-06-20 00:51:54 +00003587
John McCall48871652010-08-21 09:40:31 +00003588Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003589 AccessSpecifier AS,
3590 bool HasUsingKeyword,
3591 SourceLocation UsingLoc,
3592 CXXScopeSpec &SS,
3593 UnqualifiedId &Name,
3594 AttributeList *AttrList,
3595 bool IsTypeName,
3596 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003597 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003598
Douglas Gregor220f4272009-11-04 16:30:06 +00003599 switch (Name.getKind()) {
3600 case UnqualifiedId::IK_Identifier:
3601 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003602 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003603 case UnqualifiedId::IK_ConversionFunctionId:
3604 break;
3605
3606 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003607 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003608 // C++0x inherited constructors.
3609 if (getLangOptions().CPlusPlus0x) break;
3610
Douglas Gregor220f4272009-11-04 16:30:06 +00003611 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3612 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003613 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003614
3615 case UnqualifiedId::IK_DestructorName:
3616 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3617 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003618 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003619
3620 case UnqualifiedId::IK_TemplateId:
3621 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3622 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003623 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003624 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003625
3626 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3627 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003628 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003629 return 0;
John McCall3969e302009-12-08 07:46:18 +00003630
John McCalla0097262009-12-11 02:10:03 +00003631 // Warn about using declarations.
3632 // TODO: store that the declaration was written without 'using' and
3633 // talk about access decls instead of using decls in the
3634 // diagnostics.
3635 if (!HasUsingKeyword) {
3636 UsingLoc = Name.getSourceRange().getBegin();
3637
3638 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003639 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003640 }
3641
Douglas Gregorc4356532010-12-16 00:46:58 +00003642 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3643 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3644 return 0;
3645
John McCall3f746822009-11-17 05:59:44 +00003646 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003647 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003648 /* IsInstantiation */ false,
3649 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003650 if (UD)
3651 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003652
John McCall48871652010-08-21 09:40:31 +00003653 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003654}
3655
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003656/// \brief Determine whether a using declaration considers the given
3657/// declarations as "equivalent", e.g., if they are redeclarations of
3658/// the same entity or are both typedefs of the same type.
3659static bool
3660IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3661 bool &SuppressRedeclaration) {
3662 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3663 SuppressRedeclaration = false;
3664 return true;
3665 }
3666
3667 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3668 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3669 SuppressRedeclaration = true;
3670 return Context.hasSameType(TD1->getUnderlyingType(),
3671 TD2->getUnderlyingType());
3672 }
3673
3674 return false;
3675}
3676
3677
John McCall84d87672009-12-10 09:41:52 +00003678/// Determines whether to create a using shadow decl for a particular
3679/// decl, given the set of decls existing prior to this using lookup.
3680bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3681 const LookupResult &Previous) {
3682 // Diagnose finding a decl which is not from a base class of the
3683 // current class. We do this now because there are cases where this
3684 // function will silently decide not to build a shadow decl, which
3685 // will pre-empt further diagnostics.
3686 //
3687 // We don't need to do this in C++0x because we do the check once on
3688 // the qualifier.
3689 //
3690 // FIXME: diagnose the following if we care enough:
3691 // struct A { int foo; };
3692 // struct B : A { using A::foo; };
3693 // template <class T> struct C : A {};
3694 // template <class T> struct D : C<T> { using B::foo; } // <---
3695 // This is invalid (during instantiation) in C++03 because B::foo
3696 // resolves to the using decl in B, which is not a base class of D<T>.
3697 // We can't diagnose it immediately because C<T> is an unknown
3698 // specialization. The UsingShadowDecl in D<T> then points directly
3699 // to A::foo, which will look well-formed when we instantiate.
3700 // The right solution is to not collapse the shadow-decl chain.
3701 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3702 DeclContext *OrigDC = Orig->getDeclContext();
3703
3704 // Handle enums and anonymous structs.
3705 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3706 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3707 while (OrigRec->isAnonymousStructOrUnion())
3708 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3709
3710 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3711 if (OrigDC == CurContext) {
3712 Diag(Using->getLocation(),
3713 diag::err_using_decl_nested_name_specifier_is_current_class)
3714 << Using->getNestedNameRange();
3715 Diag(Orig->getLocation(), diag::note_using_decl_target);
3716 return true;
3717 }
3718
3719 Diag(Using->getNestedNameRange().getBegin(),
3720 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3721 << Using->getTargetNestedNameDecl()
3722 << cast<CXXRecordDecl>(CurContext)
3723 << Using->getNestedNameRange();
3724 Diag(Orig->getLocation(), diag::note_using_decl_target);
3725 return true;
3726 }
3727 }
3728
3729 if (Previous.empty()) return false;
3730
3731 NamedDecl *Target = Orig;
3732 if (isa<UsingShadowDecl>(Target))
3733 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3734
John McCalla17e83e2009-12-11 02:33:26 +00003735 // If the target happens to be one of the previous declarations, we
3736 // don't have a conflict.
3737 //
3738 // FIXME: but we might be increasing its access, in which case we
3739 // should redeclare it.
3740 NamedDecl *NonTag = 0, *Tag = 0;
3741 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3742 I != E; ++I) {
3743 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003744 bool Result;
3745 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3746 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003747
3748 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3749 }
3750
John McCall84d87672009-12-10 09:41:52 +00003751 if (Target->isFunctionOrFunctionTemplate()) {
3752 FunctionDecl *FD;
3753 if (isa<FunctionTemplateDecl>(Target))
3754 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3755 else
3756 FD = cast<FunctionDecl>(Target);
3757
3758 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003759 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003760 case Ovl_Overload:
3761 return false;
3762
3763 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003764 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003765 break;
3766
3767 // We found a decl with the exact signature.
3768 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003769 // If we're in a record, we want to hide the target, so we
3770 // return true (without a diagnostic) to tell the caller not to
3771 // build a shadow decl.
3772 if (CurContext->isRecord())
3773 return true;
3774
3775 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003776 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003777 break;
3778 }
3779
3780 Diag(Target->getLocation(), diag::note_using_decl_target);
3781 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3782 return true;
3783 }
3784
3785 // Target is not a function.
3786
John McCall84d87672009-12-10 09:41:52 +00003787 if (isa<TagDecl>(Target)) {
3788 // No conflict between a tag and a non-tag.
3789 if (!Tag) return false;
3790
John McCalle29c5cd2009-12-10 19:51:03 +00003791 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003792 Diag(Target->getLocation(), diag::note_using_decl_target);
3793 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3794 return true;
3795 }
3796
3797 // No conflict between a tag and a non-tag.
3798 if (!NonTag) return false;
3799
John McCalle29c5cd2009-12-10 19:51:03 +00003800 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003801 Diag(Target->getLocation(), diag::note_using_decl_target);
3802 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3803 return true;
3804}
3805
John McCall3f746822009-11-17 05:59:44 +00003806/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003807UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003808 UsingDecl *UD,
3809 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003810
3811 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003812 NamedDecl *Target = Orig;
3813 if (isa<UsingShadowDecl>(Target)) {
3814 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3815 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003816 }
3817
3818 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003819 = UsingShadowDecl::Create(Context, CurContext,
3820 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003821 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003822
3823 Shadow->setAccess(UD->getAccess());
3824 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3825 Shadow->setInvalidDecl();
3826
John McCall3f746822009-11-17 05:59:44 +00003827 if (S)
John McCall3969e302009-12-08 07:46:18 +00003828 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003829 else
John McCall3969e302009-12-08 07:46:18 +00003830 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003831
John McCall3969e302009-12-08 07:46:18 +00003832
John McCall84d87672009-12-10 09:41:52 +00003833 return Shadow;
3834}
John McCall3969e302009-12-08 07:46:18 +00003835
John McCall84d87672009-12-10 09:41:52 +00003836/// Hides a using shadow declaration. This is required by the current
3837/// using-decl implementation when a resolvable using declaration in a
3838/// class is followed by a declaration which would hide or override
3839/// one or more of the using decl's targets; for example:
3840///
3841/// struct Base { void foo(int); };
3842/// struct Derived : Base {
3843/// using Base::foo;
3844/// void foo(int);
3845/// };
3846///
3847/// The governing language is C++03 [namespace.udecl]p12:
3848///
3849/// When a using-declaration brings names from a base class into a
3850/// derived class scope, member functions in the derived class
3851/// override and/or hide member functions with the same name and
3852/// parameter types in a base class (rather than conflicting).
3853///
3854/// There are two ways to implement this:
3855/// (1) optimistically create shadow decls when they're not hidden
3856/// by existing declarations, or
3857/// (2) don't create any shadow decls (or at least don't make them
3858/// visible) until we've fully parsed/instantiated the class.
3859/// The problem with (1) is that we might have to retroactively remove
3860/// a shadow decl, which requires several O(n) operations because the
3861/// decl structures are (very reasonably) not designed for removal.
3862/// (2) avoids this but is very fiddly and phase-dependent.
3863void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003864 if (Shadow->getDeclName().getNameKind() ==
3865 DeclarationName::CXXConversionFunctionName)
3866 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3867
John McCall84d87672009-12-10 09:41:52 +00003868 // Remove it from the DeclContext...
3869 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003870
John McCall84d87672009-12-10 09:41:52 +00003871 // ...and the scope, if applicable...
3872 if (S) {
John McCall48871652010-08-21 09:40:31 +00003873 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003874 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003875 }
3876
John McCall84d87672009-12-10 09:41:52 +00003877 // ...and the using decl.
3878 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3879
3880 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003881 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003882}
3883
John McCalle61f2ba2009-11-18 02:36:19 +00003884/// Builds a using declaration.
3885///
3886/// \param IsInstantiation - Whether this call arises from an
3887/// instantiation of an unresolved using declaration. We treat
3888/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003889NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3890 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003891 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003892 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003893 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003894 bool IsInstantiation,
3895 bool IsTypeName,
3896 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003897 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003898 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003899 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003900
Anders Carlssonf038fc22009-08-28 05:49:21 +00003901 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003902
Anders Carlsson59140b32009-08-28 03:16:11 +00003903 if (SS.isEmpty()) {
3904 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003905 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003906 }
Mike Stump11289f42009-09-09 15:08:12 +00003907
John McCall84d87672009-12-10 09:41:52 +00003908 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003909 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003910 ForRedeclaration);
3911 Previous.setHideTags(false);
3912 if (S) {
3913 LookupName(Previous, S);
3914
3915 // It is really dumb that we have to do this.
3916 LookupResult::Filter F = Previous.makeFilter();
3917 while (F.hasNext()) {
3918 NamedDecl *D = F.next();
3919 if (!isDeclInScope(D, CurContext, S))
3920 F.erase();
3921 }
3922 F.done();
3923 } else {
3924 assert(IsInstantiation && "no scope in non-instantiation");
3925 assert(CurContext->isRecord() && "scope not record in instantiation");
3926 LookupQualifiedName(Previous, CurContext);
3927 }
3928
Mike Stump11289f42009-09-09 15:08:12 +00003929 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003930 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3931
John McCall84d87672009-12-10 09:41:52 +00003932 // Check for invalid redeclarations.
3933 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3934 return 0;
3935
3936 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003937 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3938 return 0;
3939
John McCall84c16cf2009-11-12 03:15:40 +00003940 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003941 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003942 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003943 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003944 // FIXME: not all declaration name kinds are legal here
3945 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3946 UsingLoc, TypenameLoc,
3947 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003948 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003949 } else {
3950 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003951 UsingLoc, SS.getRange(),
3952 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003953 }
John McCallb96ec562009-12-04 22:46:56 +00003954 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003955 D = UsingDecl::Create(Context, CurContext,
3956 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003957 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003958 }
John McCallb96ec562009-12-04 22:46:56 +00003959 D->setAccess(AS);
3960 CurContext->addDecl(D);
3961
3962 if (!LookupContext) return D;
3963 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003964
John McCall0b66eb32010-05-01 00:40:08 +00003965 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003966 UD->setInvalidDecl();
3967 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003968 }
3969
John McCall3969e302009-12-08 07:46:18 +00003970 // Look up the target name.
3971
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003972 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003973
John McCall3969e302009-12-08 07:46:18 +00003974 // Unlike most lookups, we don't always want to hide tag
3975 // declarations: tag names are visible through the using declaration
3976 // even if hidden by ordinary names, *except* in a dependent context
3977 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003978 if (!IsInstantiation)
3979 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003980
John McCall27b18f82009-11-17 02:14:36 +00003981 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003982
John McCall9f3059a2009-10-09 21:13:30 +00003983 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003984 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003985 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003986 UD->setInvalidDecl();
3987 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003988 }
3989
John McCallb96ec562009-12-04 22:46:56 +00003990 if (R.isAmbiguous()) {
3991 UD->setInvalidDecl();
3992 return UD;
3993 }
Mike Stump11289f42009-09-09 15:08:12 +00003994
John McCalle61f2ba2009-11-18 02:36:19 +00003995 if (IsTypeName) {
3996 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003997 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003998 Diag(IdentLoc, diag::err_using_typename_non_type);
3999 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4000 Diag((*I)->getUnderlyingDecl()->getLocation(),
4001 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004002 UD->setInvalidDecl();
4003 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004004 }
4005 } else {
4006 // If we asked for a non-typename and we got a type, error out,
4007 // but only if this is an instantiation of an unresolved using
4008 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004009 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004010 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4011 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004012 UD->setInvalidDecl();
4013 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004014 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004015 }
4016
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004017 // C++0x N2914 [namespace.udecl]p6:
4018 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004019 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004020 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4021 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004022 UD->setInvalidDecl();
4023 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004024 }
Mike Stump11289f42009-09-09 15:08:12 +00004025
John McCall84d87672009-12-10 09:41:52 +00004026 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4027 if (!CheckUsingShadowDecl(UD, *I, Previous))
4028 BuildUsingShadowDecl(S, UD, *I);
4029 }
John McCall3f746822009-11-17 05:59:44 +00004030
4031 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004032}
4033
John McCall84d87672009-12-10 09:41:52 +00004034/// Checks that the given using declaration is not an invalid
4035/// redeclaration. Note that this is checking only for the using decl
4036/// itself, not for any ill-formedness among the UsingShadowDecls.
4037bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4038 bool isTypeName,
4039 const CXXScopeSpec &SS,
4040 SourceLocation NameLoc,
4041 const LookupResult &Prev) {
4042 // C++03 [namespace.udecl]p8:
4043 // C++0x [namespace.udecl]p10:
4044 // A using-declaration is a declaration and can therefore be used
4045 // repeatedly where (and only where) multiple declarations are
4046 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004047 //
John McCall032092f2010-11-29 18:01:58 +00004048 // That's in non-member contexts.
4049 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004050 return false;
4051
4052 NestedNameSpecifier *Qual
4053 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4054
4055 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4056 NamedDecl *D = *I;
4057
4058 bool DTypename;
4059 NestedNameSpecifier *DQual;
4060 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4061 DTypename = UD->isTypeName();
4062 DQual = UD->getTargetNestedNameDecl();
4063 } else if (UnresolvedUsingValueDecl *UD
4064 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4065 DTypename = false;
4066 DQual = UD->getTargetNestedNameSpecifier();
4067 } else if (UnresolvedUsingTypenameDecl *UD
4068 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4069 DTypename = true;
4070 DQual = UD->getTargetNestedNameSpecifier();
4071 } else continue;
4072
4073 // using decls differ if one says 'typename' and the other doesn't.
4074 // FIXME: non-dependent using decls?
4075 if (isTypeName != DTypename) continue;
4076
4077 // using decls differ if they name different scopes (but note that
4078 // template instantiation can cause this check to trigger when it
4079 // didn't before instantiation).
4080 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4081 Context.getCanonicalNestedNameSpecifier(DQual))
4082 continue;
4083
4084 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004085 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004086 return true;
4087 }
4088
4089 return false;
4090}
4091
John McCall3969e302009-12-08 07:46:18 +00004092
John McCallb96ec562009-12-04 22:46:56 +00004093/// Checks that the given nested-name qualifier used in a using decl
4094/// in the current context is appropriately related to the current
4095/// scope. If an error is found, diagnoses it and returns true.
4096bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4097 const CXXScopeSpec &SS,
4098 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004099 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004100
John McCall3969e302009-12-08 07:46:18 +00004101 if (!CurContext->isRecord()) {
4102 // C++03 [namespace.udecl]p3:
4103 // C++0x [namespace.udecl]p8:
4104 // A using-declaration for a class member shall be a member-declaration.
4105
4106 // If we weren't able to compute a valid scope, it must be a
4107 // dependent class scope.
4108 if (!NamedContext || NamedContext->isRecord()) {
4109 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4110 << SS.getRange();
4111 return true;
4112 }
4113
4114 // Otherwise, everything is known to be fine.
4115 return false;
4116 }
4117
4118 // The current scope is a record.
4119
4120 // If the named context is dependent, we can't decide much.
4121 if (!NamedContext) {
4122 // FIXME: in C++0x, we can diagnose if we can prove that the
4123 // nested-name-specifier does not refer to a base class, which is
4124 // still possible in some cases.
4125
4126 // Otherwise we have to conservatively report that things might be
4127 // okay.
4128 return false;
4129 }
4130
4131 if (!NamedContext->isRecord()) {
4132 // Ideally this would point at the last name in the specifier,
4133 // but we don't have that level of source info.
4134 Diag(SS.getRange().getBegin(),
4135 diag::err_using_decl_nested_name_specifier_is_not_class)
4136 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4137 return true;
4138 }
4139
Douglas Gregor7c842292010-12-21 07:41:49 +00004140 if (!NamedContext->isDependentContext() &&
4141 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4142 return true;
4143
John McCall3969e302009-12-08 07:46:18 +00004144 if (getLangOptions().CPlusPlus0x) {
4145 // C++0x [namespace.udecl]p3:
4146 // In a using-declaration used as a member-declaration, the
4147 // nested-name-specifier shall name a base class of the class
4148 // being defined.
4149
4150 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4151 cast<CXXRecordDecl>(NamedContext))) {
4152 if (CurContext == NamedContext) {
4153 Diag(NameLoc,
4154 diag::err_using_decl_nested_name_specifier_is_current_class)
4155 << SS.getRange();
4156 return true;
4157 }
4158
4159 Diag(SS.getRange().getBegin(),
4160 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4161 << (NestedNameSpecifier*) SS.getScopeRep()
4162 << cast<CXXRecordDecl>(CurContext)
4163 << SS.getRange();
4164 return true;
4165 }
4166
4167 return false;
4168 }
4169
4170 // C++03 [namespace.udecl]p4:
4171 // A using-declaration used as a member-declaration shall refer
4172 // to a member of a base class of the class being defined [etc.].
4173
4174 // Salient point: SS doesn't have to name a base class as long as
4175 // lookup only finds members from base classes. Therefore we can
4176 // diagnose here only if we can prove that that can't happen,
4177 // i.e. if the class hierarchies provably don't intersect.
4178
4179 // TODO: it would be nice if "definitely valid" results were cached
4180 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4181 // need to be repeated.
4182
4183 struct UserData {
4184 llvm::DenseSet<const CXXRecordDecl*> Bases;
4185
4186 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4187 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4188 Data->Bases.insert(Base);
4189 return true;
4190 }
4191
4192 bool hasDependentBases(const CXXRecordDecl *Class) {
4193 return !Class->forallBases(collect, this);
4194 }
4195
4196 /// Returns true if the base is dependent or is one of the
4197 /// accumulated base classes.
4198 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4199 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4200 return !Data->Bases.count(Base);
4201 }
4202
4203 bool mightShareBases(const CXXRecordDecl *Class) {
4204 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4205 }
4206 };
4207
4208 UserData Data;
4209
4210 // Returns false if we find a dependent base.
4211 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4212 return false;
4213
4214 // Returns false if the class has a dependent base or if it or one
4215 // of its bases is present in the base set of the current context.
4216 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4217 return false;
4218
4219 Diag(SS.getRange().getBegin(),
4220 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4221 << (NestedNameSpecifier*) SS.getScopeRep()
4222 << cast<CXXRecordDecl>(CurContext)
4223 << SS.getRange();
4224
4225 return true;
John McCallb96ec562009-12-04 22:46:56 +00004226}
4227
John McCall48871652010-08-21 09:40:31 +00004228Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004229 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004230 SourceLocation AliasLoc,
4231 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004232 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004233 SourceLocation IdentLoc,
4234 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004235
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004236 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004237 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4238 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004239
Anders Carlssondca83c42009-03-28 06:23:46 +00004240 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004241 NamedDecl *PrevDecl
4242 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4243 ForRedeclaration);
4244 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4245 PrevDecl = 0;
4246
4247 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004248 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004249 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004250 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004251 // FIXME: At some point, we'll want to create the (redundant)
4252 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004253 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004254 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004255 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257
Anders Carlssondca83c42009-03-28 06:23:46 +00004258 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4259 diag::err_redefinition_different_kind;
4260 Diag(AliasLoc, DiagID) << Alias;
4261 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004262 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004263 }
4264
John McCall27b18f82009-11-17 02:14:36 +00004265 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004266 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004267
John McCall9f3059a2009-10-09 21:13:30 +00004268 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004269 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4270 CTC_NoKeywords, 0)) {
4271 if (R.getAsSingle<NamespaceDecl>() ||
4272 R.getAsSingle<NamespaceAliasDecl>()) {
4273 if (DeclContext *DC = computeDeclContext(SS, false))
4274 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4275 << Ident << DC << Corrected << SS.getRange()
4276 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4277 else
4278 Diag(IdentLoc, diag::err_using_directive_suggest)
4279 << Ident << Corrected
4280 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4281
4282 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4283 << Corrected;
4284
4285 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004286 } else {
4287 R.clear();
4288 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004289 }
4290 }
4291
4292 if (R.empty()) {
4293 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004294 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004295 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004296 }
Mike Stump11289f42009-09-09 15:08:12 +00004297
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004298 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004299 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4300 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004301 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004302 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004303
John McCalld8d0d432010-02-16 06:53:13 +00004304 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004305 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004306}
4307
Douglas Gregora57478e2010-05-01 15:04:51 +00004308namespace {
4309 /// \brief Scoped object used to handle the state changes required in Sema
4310 /// to implicitly define the body of a C++ member function;
4311 class ImplicitlyDefinedFunctionScope {
4312 Sema &S;
4313 DeclContext *PreviousContext;
4314
4315 public:
4316 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4317 : S(S), PreviousContext(S.CurContext)
4318 {
4319 S.CurContext = Method;
4320 S.PushFunctionScope();
4321 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4322 }
4323
4324 ~ImplicitlyDefinedFunctionScope() {
4325 S.PopExpressionEvaluationContext();
4326 S.PopFunctionOrBlockScope();
4327 S.CurContext = PreviousContext;
4328 }
4329 };
4330}
4331
Sebastian Redlc15c3262010-09-13 22:02:47 +00004332static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4333 CXXRecordDecl *D) {
4334 ASTContext &Context = Self.Context;
4335 QualType ClassType = Context.getTypeDeclType(D);
4336 DeclarationName ConstructorName
4337 = Context.DeclarationNames.getCXXConstructorName(
4338 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4339
4340 DeclContext::lookup_const_iterator Con, ConEnd;
4341 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4342 Con != ConEnd; ++Con) {
4343 // FIXME: In C++0x, a constructor template can be a default constructor.
4344 if (isa<FunctionTemplateDecl>(*Con))
4345 continue;
4346
4347 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4348 if (Constructor->isDefaultConstructor())
4349 return Constructor;
4350 }
4351 return 0;
4352}
4353
Douglas Gregor0be31a22010-07-02 17:43:08 +00004354CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4355 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004356 // C++ [class.ctor]p5:
4357 // A default constructor for a class X is a constructor of class X
4358 // that can be called without an argument. If there is no
4359 // user-declared constructor for class X, a default constructor is
4360 // implicitly declared. An implicitly-declared default constructor
4361 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004362 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4363 "Should not build implicit default constructor!");
4364
Douglas Gregor6d880b12010-07-01 22:31:05 +00004365 // C++ [except.spec]p14:
4366 // An implicitly declared special member function (Clause 12) shall have an
4367 // exception-specification. [...]
4368 ImplicitExceptionSpecification ExceptSpec(Context);
4369
4370 // Direct base-class destructors.
4371 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4372 BEnd = ClassDecl->bases_end();
4373 B != BEnd; ++B) {
4374 if (B->isVirtual()) // Handled below.
4375 continue;
4376
Douglas Gregor9672f922010-07-03 00:47:00 +00004377 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4378 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4379 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4380 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004381 else if (CXXConstructorDecl *Constructor
4382 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004383 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004384 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004385 }
4386
4387 // Virtual base-class destructors.
4388 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4389 BEnd = ClassDecl->vbases_end();
4390 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004391 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4392 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4393 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4394 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4395 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004396 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004397 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004398 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004399 }
4400
4401 // Field destructors.
4402 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4403 FEnd = ClassDecl->field_end();
4404 F != FEnd; ++F) {
4405 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004406 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4407 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4408 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4409 ExceptSpec.CalledDecl(
4410 DeclareImplicitDefaultConstructor(FieldClassDecl));
4411 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004412 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004413 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004414 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004415 }
John McCalldb40c7f2010-12-14 08:05:40 +00004416
4417 FunctionProtoType::ExtProtoInfo EPI;
4418 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4419 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4420 EPI.NumExceptions = ExceptSpec.size();
4421 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004422
4423 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004424 CanQualType ClassType
4425 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4426 DeclarationName Name
4427 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004428 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004429 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004430 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004431 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004432 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004433 /*TInfo=*/0,
4434 /*isExplicit=*/false,
4435 /*isInline=*/true,
4436 /*isImplicitlyDeclared=*/true);
4437 DefaultCon->setAccess(AS_public);
4438 DefaultCon->setImplicit();
4439 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004440
4441 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004442 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4443
Douglas Gregor0be31a22010-07-02 17:43:08 +00004444 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004445 PushOnScopeChains(DefaultCon, S, false);
4446 ClassDecl->addDecl(DefaultCon);
4447
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004448 return DefaultCon;
4449}
4450
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004451void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4452 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004453 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004454 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004455 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004456
Anders Carlsson423f5d82010-04-23 16:04:08 +00004457 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004458 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004459
Douglas Gregora57478e2010-05-01 15:04:51 +00004460 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004461 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004462 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004463 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004464 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004465 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004466 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004467 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004468 }
Douglas Gregor73193272010-09-20 16:48:21 +00004469
4470 SourceLocation Loc = Constructor->getLocation();
4471 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4472
4473 Constructor->setUsed();
4474 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004475}
4476
Douglas Gregor0be31a22010-07-02 17:43:08 +00004477CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004478 // C++ [class.dtor]p2:
4479 // If a class has no user-declared destructor, a destructor is
4480 // declared implicitly. An implicitly-declared destructor is an
4481 // inline public member of its class.
4482
4483 // C++ [except.spec]p14:
4484 // An implicitly declared special member function (Clause 12) shall have
4485 // an exception-specification.
4486 ImplicitExceptionSpecification ExceptSpec(Context);
4487
4488 // Direct base-class destructors.
4489 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4490 BEnd = ClassDecl->bases_end();
4491 B != BEnd; ++B) {
4492 if (B->isVirtual()) // Handled below.
4493 continue;
4494
4495 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4496 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004497 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004498 }
4499
4500 // Virtual base-class destructors.
4501 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4502 BEnd = ClassDecl->vbases_end();
4503 B != BEnd; ++B) {
4504 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4505 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004506 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004507 }
4508
4509 // Field destructors.
4510 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4511 FEnd = ClassDecl->field_end();
4512 F != FEnd; ++F) {
4513 if (const RecordType *RecordTy
4514 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4515 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004516 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004517 }
4518
Douglas Gregor7454c562010-07-02 20:37:36 +00004519 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004520 FunctionProtoType::ExtProtoInfo EPI;
4521 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4522 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4523 EPI.NumExceptions = ExceptSpec.size();
4524 EPI.Exceptions = ExceptSpec.data();
4525 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004526
4527 CanQualType ClassType
4528 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4529 DeclarationName Name
4530 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004531 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004532 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004533 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004534 /*isInline=*/true,
4535 /*isImplicitlyDeclared=*/true);
4536 Destructor->setAccess(AS_public);
4537 Destructor->setImplicit();
4538 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004539
4540 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004541 ++ASTContext::NumImplicitDestructorsDeclared;
4542
4543 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004544 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004545 PushOnScopeChains(Destructor, S, false);
4546 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004547
4548 // This could be uniqued if it ever proves significant.
4549 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4550
4551 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004552
Douglas Gregorf1203042010-07-01 19:09:28 +00004553 return Destructor;
4554}
4555
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004556void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004557 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004558 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004559 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004560 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004561 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004562
Douglas Gregor54818f02010-05-12 16:39:35 +00004563 if (Destructor->isInvalidDecl())
4564 return;
4565
Douglas Gregora57478e2010-05-01 15:04:51 +00004566 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004567
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004568 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004569 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4570 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004571
Douglas Gregor54818f02010-05-12 16:39:35 +00004572 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004573 Diag(CurrentLocation, diag::note_member_synthesized_at)
4574 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4575
4576 Destructor->setInvalidDecl();
4577 return;
4578 }
4579
Douglas Gregor73193272010-09-20 16:48:21 +00004580 SourceLocation Loc = Destructor->getLocation();
4581 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4582
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004583 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004584 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004585}
4586
Douglas Gregorb139cd52010-05-01 20:49:11 +00004587/// \brief Builds a statement that copies the given entity from \p From to
4588/// \c To.
4589///
4590/// This routine is used to copy the members of a class with an
4591/// implicitly-declared copy assignment operator. When the entities being
4592/// copied are arrays, this routine builds for loops to copy them.
4593///
4594/// \param S The Sema object used for type-checking.
4595///
4596/// \param Loc The location where the implicit copy is being generated.
4597///
4598/// \param T The type of the expressions being copied. Both expressions must
4599/// have this type.
4600///
4601/// \param To The expression we are copying to.
4602///
4603/// \param From The expression we are copying from.
4604///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004605/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4606/// Otherwise, it's a non-static member subobject.
4607///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004608/// \param Depth Internal parameter recording the depth of the recursion.
4609///
4610/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004611static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004612BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004613 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004614 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004615 // C++0x [class.copy]p30:
4616 // Each subobject is assigned in the manner appropriate to its type:
4617 //
4618 // - if the subobject is of class type, the copy assignment operator
4619 // for the class is used (as if by explicit qualification; that is,
4620 // ignoring any possible virtual overriding functions in more derived
4621 // classes);
4622 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4624
4625 // Look for operator=.
4626 DeclarationName Name
4627 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4628 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4629 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4630
4631 // Filter out any result that isn't a copy-assignment operator.
4632 LookupResult::Filter F = OpLookup.makeFilter();
4633 while (F.hasNext()) {
4634 NamedDecl *D = F.next();
4635 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4636 if (Method->isCopyAssignmentOperator())
4637 continue;
4638
4639 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004640 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004641 F.done();
4642
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004643 // Suppress the protected check (C++ [class.protected]) for each of the
4644 // assignment operators we found. This strange dance is required when
4645 // we're assigning via a base classes's copy-assignment operator. To
4646 // ensure that we're getting the right base class subobject (without
4647 // ambiguities), we need to cast "this" to that subobject type; to
4648 // ensure that we don't go through the virtual call mechanism, we need
4649 // to qualify the operator= name with the base class (see below). However,
4650 // this means that if the base class has a protected copy assignment
4651 // operator, the protected member access check will fail. So, we
4652 // rewrite "protected" access to "public" access in this case, since we
4653 // know by construction that we're calling from a derived class.
4654 if (CopyingBaseSubobject) {
4655 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4656 L != LEnd; ++L) {
4657 if (L.getAccess() == AS_protected)
4658 L.setAccess(AS_public);
4659 }
4660 }
4661
Douglas Gregorb139cd52010-05-01 20:49:11 +00004662 // Create the nested-name-specifier that will be used to qualify the
4663 // reference to operator=; this is required to suppress the virtual
4664 // call mechanism.
4665 CXXScopeSpec SS;
4666 SS.setRange(Loc);
4667 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4668 T.getTypePtr()));
4669
4670 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004671 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004672 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004673 /*FirstQualifierInScope=*/0, OpLookup,
4674 /*TemplateArgs=*/0,
4675 /*SuppressQualifierCheck=*/true);
4676 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004677 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004678
4679 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004680
John McCalldadc5752010-08-24 06:29:42 +00004681 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004682 OpEqualRef.takeAs<Expr>(),
4683 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004684 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004685 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004686
4687 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004688 }
John McCallab8c2732010-03-16 06:11:48 +00004689
Douglas Gregorb139cd52010-05-01 20:49:11 +00004690 // - if the subobject is of scalar type, the built-in assignment
4691 // operator is used.
4692 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4693 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004694 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004695 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004696 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004697
4698 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004699 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004700
4701 // - if the subobject is an array, each element is assigned, in the
4702 // manner appropriate to the element type;
4703
4704 // Construct a loop over the array bounds, e.g.,
4705 //
4706 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4707 //
4708 // that will copy each of the array elements.
4709 QualType SizeType = S.Context.getSizeType();
4710
4711 // Create the iteration variable.
4712 IdentifierInfo *IterationVarName = 0;
4713 {
4714 llvm::SmallString<8> Str;
4715 llvm::raw_svector_ostream OS(Str);
4716 OS << "__i" << Depth;
4717 IterationVarName = &S.Context.Idents.get(OS.str());
4718 }
4719 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4720 IterationVarName, SizeType,
4721 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004722 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004723
4724 // Initialize the iteration variable to zero.
4725 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004726 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004727
4728 // Create a reference to the iteration variable; we'll use this several
4729 // times throughout.
4730 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004731 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004732 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4733
4734 // Create the DeclStmt that holds the iteration variable.
4735 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4736
4737 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004738 llvm::APInt Upper
4739 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004740 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004741 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004742 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4743 BO_NE, S.Context.BoolTy,
4744 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004745
4746 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004747 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004748 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4749 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004750
4751 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004752 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4753 IterationVarRef, Loc));
4754 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4755 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004756
4757 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004758 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4759 To, From, CopyingBaseSubobject,
4760 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004761 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004762 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004763
4764 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004765 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004766 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004767 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004768 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004769}
4770
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004771/// \brief Determine whether the given class has a copy assignment operator
4772/// that accepts a const-qualified argument.
4773static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4774 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4775
4776 if (!Class->hasDeclaredCopyAssignment())
4777 S.DeclareImplicitCopyAssignment(Class);
4778
4779 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4780 DeclarationName OpName
4781 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4782
4783 DeclContext::lookup_const_iterator Op, OpEnd;
4784 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4785 // C++ [class.copy]p9:
4786 // A user-declared copy assignment operator is a non-static non-template
4787 // member function of class X with exactly one parameter of type X, X&,
4788 // const X&, volatile X& or const volatile X&.
4789 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4790 if (!Method)
4791 continue;
4792
4793 if (Method->isStatic())
4794 continue;
4795 if (Method->getPrimaryTemplate())
4796 continue;
4797 const FunctionProtoType *FnType =
4798 Method->getType()->getAs<FunctionProtoType>();
4799 assert(FnType && "Overloaded operator has no prototype.");
4800 // Don't assert on this; an invalid decl might have been left in the AST.
4801 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4802 continue;
4803 bool AcceptsConst = true;
4804 QualType ArgType = FnType->getArgType(0);
4805 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4806 ArgType = Ref->getPointeeType();
4807 // Is it a non-const lvalue reference?
4808 if (!ArgType.isConstQualified())
4809 AcceptsConst = false;
4810 }
4811 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4812 continue;
4813
4814 // We have a single argument of type cv X or cv X&, i.e. we've found the
4815 // copy assignment operator. Return whether it accepts const arguments.
4816 return AcceptsConst;
4817 }
4818 assert(Class->isInvalidDecl() &&
4819 "No copy assignment operator declared in valid code.");
4820 return false;
4821}
4822
Douglas Gregor0be31a22010-07-02 17:43:08 +00004823CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004824 // Note: The following rules are largely analoguous to the copy
4825 // constructor rules. Note that virtual bases are not taken into account
4826 // for determining the argument type of the operator. Note also that
4827 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004828
4829
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004830 // C++ [class.copy]p10:
4831 // If the class definition does not explicitly declare a copy
4832 // assignment operator, one is declared implicitly.
4833 // The implicitly-defined copy assignment operator for a class X
4834 // will have the form
4835 //
4836 // X& X::operator=(const X&)
4837 //
4838 // if
4839 bool HasConstCopyAssignment = true;
4840
4841 // -- each direct base class B of X has a copy assignment operator
4842 // whose parameter is of type const B&, const volatile B& or B,
4843 // and
4844 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4845 BaseEnd = ClassDecl->bases_end();
4846 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4847 assert(!Base->getType()->isDependentType() &&
4848 "Cannot generate implicit members for class with dependent bases.");
4849 const CXXRecordDecl *BaseClassDecl
4850 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004851 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004852 }
4853
4854 // -- for all the nonstatic data members of X that are of a class
4855 // type M (or array thereof), each such class type has a copy
4856 // assignment operator whose parameter is of type const M&,
4857 // const volatile M& or M.
4858 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4859 FieldEnd = ClassDecl->field_end();
4860 HasConstCopyAssignment && Field != FieldEnd;
4861 ++Field) {
4862 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4863 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4864 const CXXRecordDecl *FieldClassDecl
4865 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004866 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004867 }
4868 }
4869
4870 // Otherwise, the implicitly declared copy assignment operator will
4871 // have the form
4872 //
4873 // X& X::operator=(X&)
4874 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4875 QualType RetType = Context.getLValueReferenceType(ArgType);
4876 if (HasConstCopyAssignment)
4877 ArgType = ArgType.withConst();
4878 ArgType = Context.getLValueReferenceType(ArgType);
4879
Douglas Gregor68e11362010-07-01 17:48:08 +00004880 // C++ [except.spec]p14:
4881 // An implicitly declared special member function (Clause 12) shall have an
4882 // exception-specification. [...]
4883 ImplicitExceptionSpecification ExceptSpec(Context);
4884 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4885 BaseEnd = ClassDecl->bases_end();
4886 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004887 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004888 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004889
4890 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4891 DeclareImplicitCopyAssignment(BaseClassDecl);
4892
Douglas Gregor68e11362010-07-01 17:48:08 +00004893 if (CXXMethodDecl *CopyAssign
4894 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4895 ExceptSpec.CalledDecl(CopyAssign);
4896 }
4897 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4898 FieldEnd = ClassDecl->field_end();
4899 Field != FieldEnd;
4900 ++Field) {
4901 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4902 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004903 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004904 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004905
4906 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4907 DeclareImplicitCopyAssignment(FieldClassDecl);
4908
Douglas Gregor68e11362010-07-01 17:48:08 +00004909 if (CXXMethodDecl *CopyAssign
4910 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4911 ExceptSpec.CalledDecl(CopyAssign);
4912 }
4913 }
4914
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004915 // An implicitly-declared copy assignment operator is an inline public
4916 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004917 FunctionProtoType::ExtProtoInfo EPI;
4918 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4919 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4920 EPI.NumExceptions = ExceptSpec.size();
4921 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004922 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004923 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004924 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004925 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004926 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004927 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004928 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004929 /*isInline=*/true);
4930 CopyAssignment->setAccess(AS_public);
4931 CopyAssignment->setImplicit();
4932 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004933
4934 // Add the parameter to the operator.
4935 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4936 ClassDecl->getLocation(),
4937 /*Id=*/0,
4938 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004939 SC_None,
4940 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004941 CopyAssignment->setParams(&FromParam, 1);
4942
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004943 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004944 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4945
Douglas Gregor0be31a22010-07-02 17:43:08 +00004946 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004947 PushOnScopeChains(CopyAssignment, S, false);
4948 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004949
4950 AddOverriddenMethods(ClassDecl, CopyAssignment);
4951 return CopyAssignment;
4952}
4953
Douglas Gregorb139cd52010-05-01 20:49:11 +00004954void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4955 CXXMethodDecl *CopyAssignOperator) {
4956 assert((CopyAssignOperator->isImplicit() &&
4957 CopyAssignOperator->isOverloadedOperator() &&
4958 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004959 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004960 "DefineImplicitCopyAssignment called for wrong function");
4961
4962 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4963
4964 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4965 CopyAssignOperator->setInvalidDecl();
4966 return;
4967 }
4968
4969 CopyAssignOperator->setUsed();
4970
4971 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004972 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004973
4974 // C++0x [class.copy]p30:
4975 // The implicitly-defined or explicitly-defaulted copy assignment operator
4976 // for a non-union class X performs memberwise copy assignment of its
4977 // subobjects. The direct base classes of X are assigned first, in the
4978 // order of their declaration in the base-specifier-list, and then the
4979 // immediate non-static data members of X are assigned, in the order in
4980 // which they were declared in the class definition.
4981
4982 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004983 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004984
4985 // The parameter for the "other" object, which we are copying from.
4986 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4987 Qualifiers OtherQuals = Other->getType().getQualifiers();
4988 QualType OtherRefType = Other->getType();
4989 if (const LValueReferenceType *OtherRef
4990 = OtherRefType->getAs<LValueReferenceType>()) {
4991 OtherRefType = OtherRef->getPointeeType();
4992 OtherQuals = OtherRefType.getQualifiers();
4993 }
4994
4995 // Our location for everything implicitly-generated.
4996 SourceLocation Loc = CopyAssignOperator->getLocation();
4997
4998 // Construct a reference to the "other" object. We'll be using this
4999 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005000 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005001 assert(OtherRef && "Reference to parameter cannot fail!");
5002
5003 // Construct the "this" pointer. We'll be using this throughout the generated
5004 // ASTs.
5005 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5006 assert(This && "Reference to this cannot fail!");
5007
5008 // Assign base classes.
5009 bool Invalid = false;
5010 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5011 E = ClassDecl->bases_end(); Base != E; ++Base) {
5012 // Form the assignment:
5013 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5014 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005015 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005016 Invalid = true;
5017 continue;
5018 }
5019
John McCallcf142162010-08-07 06:22:56 +00005020 CXXCastPath BasePath;
5021 BasePath.push_back(Base);
5022
Douglas Gregorb139cd52010-05-01 20:49:11 +00005023 // Construct the "from" expression, which is an implicit cast to the
5024 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005025 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005026 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005027 CK_UncheckedDerivedToBase,
5028 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005029
5030 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005031 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005032
5033 // Implicitly cast "this" to the appropriately-qualified base type.
5034 Expr *ToE = To.takeAs<Expr>();
5035 ImpCastExprToType(ToE,
5036 Context.getCVRQualifiedType(BaseType,
5037 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005038 CK_UncheckedDerivedToBase,
5039 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005040 To = Owned(ToE);
5041
5042 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005043 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005044 To.get(), From,
5045 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005046 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005047 Diag(CurrentLocation, diag::note_member_synthesized_at)
5048 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5049 CopyAssignOperator->setInvalidDecl();
5050 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005051 }
5052
5053 // Success! Record the copy.
5054 Statements.push_back(Copy.takeAs<Expr>());
5055 }
5056
5057 // \brief Reference to the __builtin_memcpy function.
5058 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005059 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005060 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005061
5062 // Assign non-static members.
5063 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5064 FieldEnd = ClassDecl->field_end();
5065 Field != FieldEnd; ++Field) {
5066 // Check for members of reference type; we can't copy those.
5067 if (Field->getType()->isReferenceType()) {
5068 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5069 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5070 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005071 Diag(CurrentLocation, diag::note_member_synthesized_at)
5072 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005073 Invalid = true;
5074 continue;
5075 }
5076
5077 // Check for members of const-qualified, non-class type.
5078 QualType BaseType = Context.getBaseElementType(Field->getType());
5079 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5080 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5081 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5082 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005083 Diag(CurrentLocation, diag::note_member_synthesized_at)
5084 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005085 Invalid = true;
5086 continue;
5087 }
5088
5089 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005090 if (FieldType->isIncompleteArrayType()) {
5091 assert(ClassDecl->hasFlexibleArrayMember() &&
5092 "Incomplete array type is not valid");
5093 continue;
5094 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005095
5096 // Build references to the field in the object we're copying from and to.
5097 CXXScopeSpec SS; // Intentionally empty
5098 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5099 LookupMemberName);
5100 MemberLookup.addDecl(*Field);
5101 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005102 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005103 Loc, /*IsArrow=*/false,
5104 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005105 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005106 Loc, /*IsArrow=*/true,
5107 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005108 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5109 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5110
5111 // If the field should be copied with __builtin_memcpy rather than via
5112 // explicit assignments, do so. This optimization only applies for arrays
5113 // of scalars and arrays of class type with trivial copy-assignment
5114 // operators.
5115 if (FieldType->isArrayType() &&
5116 (!BaseType->isRecordType() ||
5117 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5118 ->hasTrivialCopyAssignment())) {
5119 // Compute the size of the memory buffer to be copied.
5120 QualType SizeType = Context.getSizeType();
5121 llvm::APInt Size(Context.getTypeSize(SizeType),
5122 Context.getTypeSizeInChars(BaseType).getQuantity());
5123 for (const ConstantArrayType *Array
5124 = Context.getAsConstantArrayType(FieldType);
5125 Array;
5126 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005127 llvm::APInt ArraySize
5128 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005129 Size *= ArraySize;
5130 }
5131
5132 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005133 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5134 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005135
5136 bool NeedsCollectableMemCpy =
5137 (BaseType->isRecordType() &&
5138 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5139
5140 if (NeedsCollectableMemCpy) {
5141 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005142 // Create a reference to the __builtin_objc_memmove_collectable function.
5143 LookupResult R(*this,
5144 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005145 Loc, LookupOrdinaryName);
5146 LookupName(R, TUScope, true);
5147
5148 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5149 if (!CollectableMemCpy) {
5150 // Something went horribly wrong earlier, and we will have
5151 // complained about it.
5152 Invalid = true;
5153 continue;
5154 }
5155
5156 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5157 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005158 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005159 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5160 }
5161 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005162 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005163 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005164 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5165 LookupOrdinaryName);
5166 LookupName(R, TUScope, true);
5167
5168 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5169 if (!BuiltinMemCpy) {
5170 // Something went horribly wrong earlier, and we will have complained
5171 // about it.
5172 Invalid = true;
5173 continue;
5174 }
5175
5176 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5177 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005178 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005179 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5180 }
5181
John McCall37ad5512010-08-23 06:44:23 +00005182 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005183 CallArgs.push_back(To.takeAs<Expr>());
5184 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005185 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005186 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005187 if (NeedsCollectableMemCpy)
5188 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005189 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005190 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005191 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005192 else
5193 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005194 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005195 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005196 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005197
Douglas Gregorb139cd52010-05-01 20:49:11 +00005198 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5199 Statements.push_back(Call.takeAs<Expr>());
5200 continue;
5201 }
5202
5203 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005204 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005205 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005206 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005207 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005208 Diag(CurrentLocation, diag::note_member_synthesized_at)
5209 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5210 CopyAssignOperator->setInvalidDecl();
5211 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005212 }
5213
5214 // Success! Record the copy.
5215 Statements.push_back(Copy.takeAs<Stmt>());
5216 }
5217
5218 if (!Invalid) {
5219 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005220 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005221
John McCalldadc5752010-08-24 06:29:42 +00005222 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005223 if (Return.isInvalid())
5224 Invalid = true;
5225 else {
5226 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005227
5228 if (Trap.hasErrorOccurred()) {
5229 Diag(CurrentLocation, diag::note_member_synthesized_at)
5230 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5231 Invalid = true;
5232 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005233 }
5234 }
5235
5236 if (Invalid) {
5237 CopyAssignOperator->setInvalidDecl();
5238 return;
5239 }
5240
John McCalldadc5752010-08-24 06:29:42 +00005241 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005242 /*isStmtExpr=*/false);
5243 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5244 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005245}
5246
Douglas Gregor0be31a22010-07-02 17:43:08 +00005247CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5248 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005249 // C++ [class.copy]p4:
5250 // If the class definition does not explicitly declare a copy
5251 // constructor, one is declared implicitly.
5252
Douglas Gregor54be3392010-07-01 17:57:27 +00005253 // C++ [class.copy]p5:
5254 // The implicitly-declared copy constructor for a class X will
5255 // have the form
5256 //
5257 // X::X(const X&)
5258 //
5259 // if
5260 bool HasConstCopyConstructor = true;
5261
5262 // -- each direct or virtual base class B of X has a copy
5263 // constructor whose first parameter is of type const B& or
5264 // const volatile B&, and
5265 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5266 BaseEnd = ClassDecl->bases_end();
5267 HasConstCopyConstructor && Base != BaseEnd;
5268 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005269 // Virtual bases are handled below.
5270 if (Base->isVirtual())
5271 continue;
5272
Douglas Gregora6d69502010-07-02 23:41:54 +00005273 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005274 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005275 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5276 DeclareImplicitCopyConstructor(BaseClassDecl);
5277
Douglas Gregorcfe68222010-07-01 18:27:03 +00005278 HasConstCopyConstructor
5279 = BaseClassDecl->hasConstCopyConstructor(Context);
5280 }
5281
5282 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5283 BaseEnd = ClassDecl->vbases_end();
5284 HasConstCopyConstructor && Base != BaseEnd;
5285 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005286 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005287 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005288 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5289 DeclareImplicitCopyConstructor(BaseClassDecl);
5290
Douglas Gregor54be3392010-07-01 17:57:27 +00005291 HasConstCopyConstructor
5292 = BaseClassDecl->hasConstCopyConstructor(Context);
5293 }
5294
5295 // -- for all the nonstatic data members of X that are of a
5296 // class type M (or array thereof), each such class type
5297 // has a copy constructor whose first parameter is of type
5298 // const M& or const volatile M&.
5299 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5300 FieldEnd = ClassDecl->field_end();
5301 HasConstCopyConstructor && Field != FieldEnd;
5302 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005303 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005304 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005305 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005306 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005307 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5308 DeclareImplicitCopyConstructor(FieldClassDecl);
5309
Douglas Gregor54be3392010-07-01 17:57:27 +00005310 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005311 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005312 }
5313 }
5314
5315 // Otherwise, the implicitly declared copy constructor will have
5316 // the form
5317 //
5318 // X::X(X&)
5319 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5320 QualType ArgType = ClassType;
5321 if (HasConstCopyConstructor)
5322 ArgType = ArgType.withConst();
5323 ArgType = Context.getLValueReferenceType(ArgType);
5324
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005325 // C++ [except.spec]p14:
5326 // An implicitly declared special member function (Clause 12) shall have an
5327 // exception-specification. [...]
5328 ImplicitExceptionSpecification ExceptSpec(Context);
5329 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5330 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5331 BaseEnd = ClassDecl->bases_end();
5332 Base != BaseEnd;
5333 ++Base) {
5334 // Virtual bases are handled below.
5335 if (Base->isVirtual())
5336 continue;
5337
Douglas Gregora6d69502010-07-02 23:41:54 +00005338 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005339 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005340 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5341 DeclareImplicitCopyConstructor(BaseClassDecl);
5342
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005343 if (CXXConstructorDecl *CopyConstructor
5344 = BaseClassDecl->getCopyConstructor(Context, Quals))
5345 ExceptSpec.CalledDecl(CopyConstructor);
5346 }
5347 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5348 BaseEnd = ClassDecl->vbases_end();
5349 Base != BaseEnd;
5350 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005351 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005352 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005353 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5354 DeclareImplicitCopyConstructor(BaseClassDecl);
5355
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005356 if (CXXConstructorDecl *CopyConstructor
5357 = BaseClassDecl->getCopyConstructor(Context, Quals))
5358 ExceptSpec.CalledDecl(CopyConstructor);
5359 }
5360 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5361 FieldEnd = ClassDecl->field_end();
5362 Field != FieldEnd;
5363 ++Field) {
5364 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5365 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005366 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005367 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005368 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5369 DeclareImplicitCopyConstructor(FieldClassDecl);
5370
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005371 if (CXXConstructorDecl *CopyConstructor
5372 = FieldClassDecl->getCopyConstructor(Context, Quals))
5373 ExceptSpec.CalledDecl(CopyConstructor);
5374 }
5375 }
5376
Douglas Gregor54be3392010-07-01 17:57:27 +00005377 // An implicitly-declared copy constructor is an inline public
5378 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005379 FunctionProtoType::ExtProtoInfo EPI;
5380 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5381 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5382 EPI.NumExceptions = ExceptSpec.size();
5383 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005384 DeclarationName Name
5385 = Context.DeclarationNames.getCXXConstructorName(
5386 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005387 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005388 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005389 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005390 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005391 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005392 /*TInfo=*/0,
5393 /*isExplicit=*/false,
5394 /*isInline=*/true,
5395 /*isImplicitlyDeclared=*/true);
5396 CopyConstructor->setAccess(AS_public);
5397 CopyConstructor->setImplicit();
5398 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5399
Douglas Gregora6d69502010-07-02 23:41:54 +00005400 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005401 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5402
Douglas Gregor54be3392010-07-01 17:57:27 +00005403 // Add the parameter to the constructor.
5404 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5405 ClassDecl->getLocation(),
5406 /*IdentifierInfo=*/0,
5407 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005408 SC_None,
5409 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005410 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005411 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005412 PushOnScopeChains(CopyConstructor, S, false);
5413 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005414
5415 return CopyConstructor;
5416}
5417
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005418void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5419 CXXConstructorDecl *CopyConstructor,
5420 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005421 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005422 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005423 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005424 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005425
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005426 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005427 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005428
Douglas Gregora57478e2010-05-01 15:04:51 +00005429 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005430 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005431
Alexis Hunt1d792652011-01-08 20:30:50 +00005432 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005433 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005434 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005435 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005436 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005437 } else {
5438 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5439 CopyConstructor->getLocation(),
5440 MultiStmtArg(*this, 0, 0),
5441 /*isStmtExpr=*/false)
5442 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005443 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005444
5445 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005446}
5447
John McCalldadc5752010-08-24 06:29:42 +00005448ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005449Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005450 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005451 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005452 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005453 unsigned ConstructKind,
5454 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005455 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005456
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005457 // C++0x [class.copy]p34:
5458 // When certain criteria are met, an implementation is allowed to
5459 // omit the copy/move construction of a class object, even if the
5460 // copy/move constructor and/or destructor for the object have
5461 // side effects. [...]
5462 // - when a temporary class object that has not been bound to a
5463 // reference (12.2) would be copied/moved to a class object
5464 // with the same cv-unqualified type, the copy/move operation
5465 // can be omitted by constructing the temporary object
5466 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005467 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5468 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005469 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005470 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472
5473 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005474 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005475 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005476}
5477
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005478/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5479/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005480ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005481Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5482 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005483 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005484 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005485 unsigned ConstructKind,
5486 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005487 unsigned NumExprs = ExprArgs.size();
5488 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005489
Douglas Gregor27381f32009-11-23 12:27:39 +00005490 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005491 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005492 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005493 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005494 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5495 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005496}
5497
Mike Stump11289f42009-09-09 15:08:12 +00005498bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005499 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005500 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005501 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005502 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005503 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005504 move(Exprs), false, CXXConstructExpr::CK_Complete,
5505 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005506 if (TempResult.isInvalid())
5507 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005508
Anders Carlsson6eb55572009-08-25 05:12:04 +00005509 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005510 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005511 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005512 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005513 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005514
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005515 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005516}
5517
John McCall03c48482010-02-02 09:10:11 +00005518void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5519 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005520 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005521 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005522 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005523 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005524 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005525 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005526 << VD->getDeclName()
5527 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005528
John McCall386dfc72010-09-18 05:25:11 +00005529 // TODO: this should be re-enabled for static locals by !CXAAtExit
5530 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005531 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005532 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005533}
5534
Mike Stump11289f42009-09-09 15:08:12 +00005535/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005536/// ActOnDeclarator, when a C++ direct initializer is present.
5537/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005538void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005539 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005540 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005541 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005542 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005543
5544 // If there is no declaration, there was an error parsing it. Just ignore
5545 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005546 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005547 return;
Mike Stump11289f42009-09-09 15:08:12 +00005548
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005549 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5550 if (!VDecl) {
5551 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5552 RealDecl->setInvalidDecl();
5553 return;
5554 }
5555
Douglas Gregor402250f2009-08-26 21:14:46 +00005556 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005557 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005558 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5559 //
5560 // Clients that want to distinguish between the two forms, can check for
5561 // direct initializer using VarDecl::hasCXXDirectInitializer().
5562 // A major benefit is that clients that don't particularly care about which
5563 // exactly form was it (like the CodeGen) can handle both cases without
5564 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005565
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005566 // C++ 8.5p11:
5567 // The form of initialization (using parentheses or '=') is generally
5568 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005569 // class type.
5570
Douglas Gregor50dc2192010-02-11 22:55:30 +00005571 if (!VDecl->getType()->isDependentType() &&
5572 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005573 diag::err_typecheck_decl_incomplete_type)) {
5574 VDecl->setInvalidDecl();
5575 return;
5576 }
5577
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005578 // The variable can not have an abstract class type.
5579 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5580 diag::err_abstract_type_in_decl,
5581 AbstractVariableType))
5582 VDecl->setInvalidDecl();
5583
Sebastian Redl5ca79842010-02-01 20:16:42 +00005584 const VarDecl *Def;
5585 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005586 Diag(VDecl->getLocation(), diag::err_redefinition)
5587 << VDecl->getDeclName();
5588 Diag(Def->getLocation(), diag::note_previous_definition);
5589 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005590 return;
5591 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005592
Douglas Gregorf0f83692010-08-24 05:27:49 +00005593 // C++ [class.static.data]p4
5594 // If a static data member is of const integral or const
5595 // enumeration type, its declaration in the class definition can
5596 // specify a constant-initializer which shall be an integral
5597 // constant expression (5.19). In that case, the member can appear
5598 // in integral constant expressions. The member shall still be
5599 // defined in a namespace scope if it is used in the program and the
5600 // namespace scope definition shall not contain an initializer.
5601 //
5602 // We already performed a redefinition check above, but for static
5603 // data members we also need to check whether there was an in-class
5604 // declaration with an initializer.
5605 const VarDecl* PrevInit = 0;
5606 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5607 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5608 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5609 return;
5610 }
5611
Douglas Gregor71f39c92010-12-16 01:31:22 +00005612 bool IsDependent = false;
5613 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5614 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5615 VDecl->setInvalidDecl();
5616 return;
5617 }
5618
5619 if (Exprs.get()[I]->isTypeDependent())
5620 IsDependent = true;
5621 }
5622
Douglas Gregor50dc2192010-02-11 22:55:30 +00005623 // If either the declaration has a dependent type or if any of the
5624 // expressions is type-dependent, we represent the initialization
5625 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005626 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005627 // Let clients know that initialization was done with a direct initializer.
5628 VDecl->setCXXDirectInitializer(true);
5629
5630 // Store the initialization expressions as a ParenListExpr.
5631 unsigned NumExprs = Exprs.size();
5632 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5633 (Expr **)Exprs.release(),
5634 NumExprs, RParenLoc));
5635 return;
5636 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005637
5638 // Capture the variable that is being initialized and the style of
5639 // initialization.
5640 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5641
5642 // FIXME: Poor source location information.
5643 InitializationKind Kind
5644 = InitializationKind::CreateDirect(VDecl->getLocation(),
5645 LParenLoc, RParenLoc);
5646
5647 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005648 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005649 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005650 if (Result.isInvalid()) {
5651 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005652 return;
5653 }
John McCallacf0ee52010-10-08 02:01:28 +00005654
5655 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005656
Douglas Gregora40433a2010-12-07 00:41:46 +00005657 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005658 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005659 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005660
John McCall8b7fd8f12011-01-19 11:48:09 +00005661 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005662}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005663
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005664/// \brief Given a constructor and the set of arguments provided for the
5665/// constructor, convert the arguments and add any required default arguments
5666/// to form a proper call to this constructor.
5667///
5668/// \returns true if an error occurred, false otherwise.
5669bool
5670Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5671 MultiExprArg ArgsPtr,
5672 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005673 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005674 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5675 unsigned NumArgs = ArgsPtr.size();
5676 Expr **Args = (Expr **)ArgsPtr.get();
5677
5678 const FunctionProtoType *Proto
5679 = Constructor->getType()->getAs<FunctionProtoType>();
5680 assert(Proto && "Constructor without a prototype?");
5681 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005682
5683 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005684 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005685 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005686 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005687 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005688
5689 VariadicCallType CallType =
5690 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5691 llvm::SmallVector<Expr *, 8> AllArgs;
5692 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5693 Proto, 0, Args, NumArgs, AllArgs,
5694 CallType);
5695 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5696 ConvertedArgs.push_back(AllArgs[i]);
5697 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005698}
5699
Anders Carlssone363c8e2009-12-12 00:32:00 +00005700static inline bool
5701CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5702 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005703 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005704 if (isa<NamespaceDecl>(DC)) {
5705 return SemaRef.Diag(FnDecl->getLocation(),
5706 diag::err_operator_new_delete_declared_in_namespace)
5707 << FnDecl->getDeclName();
5708 }
5709
5710 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005711 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005712 return SemaRef.Diag(FnDecl->getLocation(),
5713 diag::err_operator_new_delete_declared_static)
5714 << FnDecl->getDeclName();
5715 }
5716
Anders Carlsson60659a82009-12-12 02:43:16 +00005717 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005718}
5719
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005720static inline bool
5721CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5722 CanQualType ExpectedResultType,
5723 CanQualType ExpectedFirstParamType,
5724 unsigned DependentParamTypeDiag,
5725 unsigned InvalidParamTypeDiag) {
5726 QualType ResultType =
5727 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5728
5729 // Check that the result type is not dependent.
5730 if (ResultType->isDependentType())
5731 return SemaRef.Diag(FnDecl->getLocation(),
5732 diag::err_operator_new_delete_dependent_result_type)
5733 << FnDecl->getDeclName() << ExpectedResultType;
5734
5735 // Check that the result type is what we expect.
5736 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5737 return SemaRef.Diag(FnDecl->getLocation(),
5738 diag::err_operator_new_delete_invalid_result_type)
5739 << FnDecl->getDeclName() << ExpectedResultType;
5740
5741 // A function template must have at least 2 parameters.
5742 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5743 return SemaRef.Diag(FnDecl->getLocation(),
5744 diag::err_operator_new_delete_template_too_few_parameters)
5745 << FnDecl->getDeclName();
5746
5747 // The function decl must have at least 1 parameter.
5748 if (FnDecl->getNumParams() == 0)
5749 return SemaRef.Diag(FnDecl->getLocation(),
5750 diag::err_operator_new_delete_too_few_parameters)
5751 << FnDecl->getDeclName();
5752
5753 // Check the the first parameter type is not dependent.
5754 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5755 if (FirstParamType->isDependentType())
5756 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5757 << FnDecl->getDeclName() << ExpectedFirstParamType;
5758
5759 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005760 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005761 ExpectedFirstParamType)
5762 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5763 << FnDecl->getDeclName() << ExpectedFirstParamType;
5764
5765 return false;
5766}
5767
Anders Carlsson12308f42009-12-11 23:23:22 +00005768static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005769CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005770 // C++ [basic.stc.dynamic.allocation]p1:
5771 // A program is ill-formed if an allocation function is declared in a
5772 // namespace scope other than global scope or declared static in global
5773 // scope.
5774 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5775 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005776
5777 CanQualType SizeTy =
5778 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5779
5780 // C++ [basic.stc.dynamic.allocation]p1:
5781 // The return type shall be void*. The first parameter shall have type
5782 // std::size_t.
5783 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5784 SizeTy,
5785 diag::err_operator_new_dependent_param_type,
5786 diag::err_operator_new_param_type))
5787 return true;
5788
5789 // C++ [basic.stc.dynamic.allocation]p1:
5790 // The first parameter shall not have an associated default argument.
5791 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005792 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005793 diag::err_operator_new_default_arg)
5794 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5795
5796 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005797}
5798
5799static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005800CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5801 // C++ [basic.stc.dynamic.deallocation]p1:
5802 // A program is ill-formed if deallocation functions are declared in a
5803 // namespace scope other than global scope or declared static in global
5804 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005805 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5806 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005807
5808 // C++ [basic.stc.dynamic.deallocation]p2:
5809 // Each deallocation function shall return void and its first parameter
5810 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005811 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5812 SemaRef.Context.VoidPtrTy,
5813 diag::err_operator_delete_dependent_param_type,
5814 diag::err_operator_delete_param_type))
5815 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005816
Anders Carlsson12308f42009-12-11 23:23:22 +00005817 return false;
5818}
5819
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005820/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5821/// of this overloaded operator is well-formed. If so, returns false;
5822/// otherwise, emits appropriate diagnostics and returns true.
5823bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005824 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005825 "Expected an overloaded operator declaration");
5826
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005827 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5828
Mike Stump11289f42009-09-09 15:08:12 +00005829 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005830 // The allocation and deallocation functions, operator new,
5831 // operator new[], operator delete and operator delete[], are
5832 // described completely in 3.7.3. The attributes and restrictions
5833 // found in the rest of this subclause do not apply to them unless
5834 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005835 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005836 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005837
Anders Carlsson22f443f2009-12-12 00:26:23 +00005838 if (Op == OO_New || Op == OO_Array_New)
5839 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005840
5841 // C++ [over.oper]p6:
5842 // An operator function shall either be a non-static member
5843 // function or be a non-member function and have at least one
5844 // parameter whose type is a class, a reference to a class, an
5845 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005846 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5847 if (MethodDecl->isStatic())
5848 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005849 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005850 } else {
5851 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005852 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5853 ParamEnd = FnDecl->param_end();
5854 Param != ParamEnd; ++Param) {
5855 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005856 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5857 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005858 ClassOrEnumParam = true;
5859 break;
5860 }
5861 }
5862
Douglas Gregord69246b2008-11-17 16:14:12 +00005863 if (!ClassOrEnumParam)
5864 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005865 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005866 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005867 }
5868
5869 // C++ [over.oper]p8:
5870 // An operator function cannot have default arguments (8.3.6),
5871 // except where explicitly stated below.
5872 //
Mike Stump11289f42009-09-09 15:08:12 +00005873 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005874 // (C++ [over.call]p1).
5875 if (Op != OO_Call) {
5876 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5877 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005878 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005879 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005880 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005881 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005882 }
5883 }
5884
Douglas Gregor6cf08062008-11-10 13:38:07 +00005885 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5886 { false, false, false }
5887#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5888 , { Unary, Binary, MemberOnly }
5889#include "clang/Basic/OperatorKinds.def"
5890 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005891
Douglas Gregor6cf08062008-11-10 13:38:07 +00005892 bool CanBeUnaryOperator = OperatorUses[Op][0];
5893 bool CanBeBinaryOperator = OperatorUses[Op][1];
5894 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005895
5896 // C++ [over.oper]p8:
5897 // [...] Operator functions cannot have more or fewer parameters
5898 // than the number required for the corresponding operator, as
5899 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005900 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005901 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005902 if (Op != OO_Call &&
5903 ((NumParams == 1 && !CanBeUnaryOperator) ||
5904 (NumParams == 2 && !CanBeBinaryOperator) ||
5905 (NumParams < 1) || (NumParams > 2))) {
5906 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005907 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005908 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005909 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005910 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005911 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005912 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005913 assert(CanBeBinaryOperator &&
5914 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005915 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005916 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005917
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005918 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005919 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005920 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005921
Douglas Gregord69246b2008-11-17 16:14:12 +00005922 // Overloaded operators other than operator() cannot be variadic.
5923 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005924 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005925 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005926 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005927 }
5928
5929 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005930 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5931 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005932 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005933 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005934 }
5935
5936 // C++ [over.inc]p1:
5937 // The user-defined function called operator++ implements the
5938 // prefix and postfix ++ operator. If this function is a member
5939 // function with no parameters, or a non-member function with one
5940 // parameter of class or enumeration type, it defines the prefix
5941 // increment operator ++ for objects of that type. If the function
5942 // is a member function with one parameter (which shall be of type
5943 // int) or a non-member function with two parameters (the second
5944 // of which shall be of type int), it defines the postfix
5945 // increment operator ++ for objects of that type.
5946 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5947 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5948 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005949 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005950 ParamIsInt = BT->getKind() == BuiltinType::Int;
5951
Chris Lattner2b786902008-11-21 07:50:02 +00005952 if (!ParamIsInt)
5953 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005954 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005955 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005956 }
5957
Douglas Gregord69246b2008-11-17 16:14:12 +00005958 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005959}
Chris Lattner3b024a32008-12-17 07:09:26 +00005960
Alexis Huntc88db062010-01-13 09:01:02 +00005961/// CheckLiteralOperatorDeclaration - Check whether the declaration
5962/// of this literal operator function is well-formed. If so, returns
5963/// false; otherwise, emits appropriate diagnostics and returns true.
5964bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5965 DeclContext *DC = FnDecl->getDeclContext();
5966 Decl::Kind Kind = DC->getDeclKind();
5967 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5968 Kind != Decl::LinkageSpec) {
5969 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5970 << FnDecl->getDeclName();
5971 return true;
5972 }
5973
5974 bool Valid = false;
5975
Alexis Hunt7dd26172010-04-07 23:11:06 +00005976 // template <char...> type operator "" name() is the only valid template
5977 // signature, and the only valid signature with no parameters.
5978 if (FnDecl->param_size() == 0) {
5979 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5980 // Must have only one template parameter
5981 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5982 if (Params->size() == 1) {
5983 NonTypeTemplateParmDecl *PmDecl =
5984 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005985
Alexis Hunt7dd26172010-04-07 23:11:06 +00005986 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00005987 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5988 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5989 Valid = true;
5990 }
5991 }
5992 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005993 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005994 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5995
Alexis Huntc88db062010-01-13 09:01:02 +00005996 QualType T = (*Param)->getType();
5997
Alexis Hunt079a6f72010-04-07 22:57:35 +00005998 // unsigned long long int, long double, and any character type are allowed
5999 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006000 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6001 Context.hasSameType(T, Context.LongDoubleTy) ||
6002 Context.hasSameType(T, Context.CharTy) ||
6003 Context.hasSameType(T, Context.WCharTy) ||
6004 Context.hasSameType(T, Context.Char16Ty) ||
6005 Context.hasSameType(T, Context.Char32Ty)) {
6006 if (++Param == FnDecl->param_end())
6007 Valid = true;
6008 goto FinishedParams;
6009 }
6010
Alexis Hunt079a6f72010-04-07 22:57:35 +00006011 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006012 const PointerType *PT = T->getAs<PointerType>();
6013 if (!PT)
6014 goto FinishedParams;
6015 T = PT->getPointeeType();
6016 if (!T.isConstQualified())
6017 goto FinishedParams;
6018 T = T.getUnqualifiedType();
6019
6020 // Move on to the second parameter;
6021 ++Param;
6022
6023 // If there is no second parameter, the first must be a const char *
6024 if (Param == FnDecl->param_end()) {
6025 if (Context.hasSameType(T, Context.CharTy))
6026 Valid = true;
6027 goto FinishedParams;
6028 }
6029
6030 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6031 // are allowed as the first parameter to a two-parameter function
6032 if (!(Context.hasSameType(T, Context.CharTy) ||
6033 Context.hasSameType(T, Context.WCharTy) ||
6034 Context.hasSameType(T, Context.Char16Ty) ||
6035 Context.hasSameType(T, Context.Char32Ty)))
6036 goto FinishedParams;
6037
6038 // The second and final parameter must be an std::size_t
6039 T = (*Param)->getType().getUnqualifiedType();
6040 if (Context.hasSameType(T, Context.getSizeType()) &&
6041 ++Param == FnDecl->param_end())
6042 Valid = true;
6043 }
6044
6045 // FIXME: This diagnostic is absolutely terrible.
6046FinishedParams:
6047 if (!Valid) {
6048 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6049 << FnDecl->getDeclName();
6050 return true;
6051 }
6052
6053 return false;
6054}
6055
Douglas Gregor07665a62009-01-05 19:45:36 +00006056/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6057/// linkage specification, including the language and (if present)
6058/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6059/// the location of the language string literal, which is provided
6060/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6061/// the '{' brace. Otherwise, this linkage specification does not
6062/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006063Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6064 SourceLocation LangLoc,
6065 llvm::StringRef Lang,
6066 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006067 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006068 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006069 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006070 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006071 Language = LinkageSpecDecl::lang_cxx;
6072 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006073 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006074 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006075 }
Mike Stump11289f42009-09-09 15:08:12 +00006076
Chris Lattner438e5012008-12-17 07:13:27 +00006077 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006078
Douglas Gregor07665a62009-01-05 19:45:36 +00006079 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006080 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006081 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006082 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006083 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006084 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006085}
6086
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006087/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006088/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6089/// valid, it's the position of the closing '}' brace in a linkage
6090/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006091Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6092 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006093 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006094 if (LinkageSpec)
6095 PopDeclContext();
6096 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006097}
6098
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006099/// \brief Perform semantic analysis for the variable declaration that
6100/// occurs within a C++ catch clause, returning the newly-created
6101/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006102VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006103 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006104 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006105 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006106 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006107 QualType ExDeclType = TInfo->getType();
6108
Sebastian Redl54c04d42008-12-22 19:15:10 +00006109 // Arrays and functions decay.
6110 if (ExDeclType->isArrayType())
6111 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6112 else if (ExDeclType->isFunctionType())
6113 ExDeclType = Context.getPointerType(ExDeclType);
6114
6115 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6116 // The exception-declaration shall not denote a pointer or reference to an
6117 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006118 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006119 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006120 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006121 Invalid = true;
6122 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006123
Douglas Gregor104ee002010-03-08 01:47:36 +00006124 // GCC allows catching pointers and references to incomplete types
6125 // as an extension; so do we, but we warn by default.
6126
Sebastian Redl54c04d42008-12-22 19:15:10 +00006127 QualType BaseType = ExDeclType;
6128 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006129 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006130 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006131 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006132 BaseType = Ptr->getPointeeType();
6133 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006134 DK = diag::ext_catch_incomplete_ptr;
6135 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006136 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006137 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006138 BaseType = Ref->getPointeeType();
6139 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006140 DK = diag::ext_catch_incomplete_ref;
6141 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006142 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006143 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006144 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6145 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006146 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006147
Mike Stump11289f42009-09-09 15:08:12 +00006148 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006149 RequireNonAbstractType(Loc, ExDeclType,
6150 diag::err_abstract_type_in_decl,
6151 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006152 Invalid = true;
6153
John McCall2ca705e2010-07-24 00:37:23 +00006154 // Only the non-fragile NeXT runtime currently supports C++ catches
6155 // of ObjC types, and no runtime supports catching ObjC types by value.
6156 if (!Invalid && getLangOptions().ObjC1) {
6157 QualType T = ExDeclType;
6158 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6159 T = RT->getPointeeType();
6160
6161 if (T->isObjCObjectType()) {
6162 Diag(Loc, diag::err_objc_object_catch);
6163 Invalid = true;
6164 } else if (T->isObjCObjectPointerType()) {
6165 if (!getLangOptions().NeXTRuntime) {
6166 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6167 Invalid = true;
6168 } else if (!getLangOptions().ObjCNonFragileABI) {
6169 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6170 Invalid = true;
6171 }
6172 }
6173 }
6174
Mike Stump11289f42009-09-09 15:08:12 +00006175 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006176 Name, ExDeclType, TInfo, SC_None,
6177 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006178 ExDecl->setExceptionVariable(true);
6179
Douglas Gregor6de584c2010-03-05 23:38:39 +00006180 if (!Invalid) {
6181 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6182 // C++ [except.handle]p16:
6183 // The object declared in an exception-declaration or, if the
6184 // exception-declaration does not specify a name, a temporary (12.2) is
6185 // copy-initialized (8.5) from the exception object. [...]
6186 // The object is destroyed when the handler exits, after the destruction
6187 // of any automatic objects initialized within the handler.
6188 //
6189 // We just pretend to initialize the object with itself, then make sure
6190 // it can be destroyed later.
6191 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6192 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006193 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006194 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6195 SourceLocation());
6196 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006197 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006198 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006199 if (Result.isInvalid())
6200 Invalid = true;
6201 else
6202 FinalizeVarWithDestructor(ExDecl, RecordTy);
6203 }
6204 }
6205
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006206 if (Invalid)
6207 ExDecl->setInvalidDecl();
6208
6209 return ExDecl;
6210}
6211
6212/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6213/// handler.
John McCall48871652010-08-21 09:40:31 +00006214Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006215 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006216 bool Invalid = D.isInvalidType();
6217
6218 // Check for unexpanded parameter packs.
6219 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6220 UPPC_ExceptionType)) {
6221 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6222 D.getIdentifierLoc());
6223 Invalid = true;
6224 }
6225
Sebastian Redl54c04d42008-12-22 19:15:10 +00006226 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006227 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006228 LookupOrdinaryName,
6229 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006230 // The scope should be freshly made just for us. There is just no way
6231 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006232 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006233 if (PrevDecl->isTemplateParameter()) {
6234 // Maybe we will complain about the shadowed template parameter.
6235 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006236 }
6237 }
6238
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006239 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006240 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6241 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006242 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006243 }
6244
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006245 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006246 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006247 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006248
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006249 if (Invalid)
6250 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006251
Sebastian Redl54c04d42008-12-22 19:15:10 +00006252 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006253 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006254 PushOnScopeChains(ExDecl, S);
6255 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006256 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006257
Douglas Gregor758a8692009-06-17 21:51:59 +00006258 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006259 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006260}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006261
John McCall48871652010-08-21 09:40:31 +00006262Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006263 Expr *AssertExpr,
6264 Expr *AssertMessageExpr_) {
6265 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006266
Anders Carlsson54b26982009-03-14 00:33:21 +00006267 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6268 llvm::APSInt Value(32);
6269 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6270 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6271 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006272 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006273 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006274
Anders Carlsson54b26982009-03-14 00:33:21 +00006275 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006276 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006277 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006278 }
6279 }
Mike Stump11289f42009-09-09 15:08:12 +00006280
Douglas Gregoref68fee2010-12-15 23:55:21 +00006281 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6282 return 0;
6283
Mike Stump11289f42009-09-09 15:08:12 +00006284 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006285 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006286
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006287 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006288 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006289}
Sebastian Redlf769df52009-03-24 22:27:57 +00006290
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006291/// \brief Perform semantic analysis of the given friend type declaration.
6292///
6293/// \returns A friend declaration that.
6294FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6295 TypeSourceInfo *TSInfo) {
6296 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6297
6298 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006299 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006300
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006301 if (!getLangOptions().CPlusPlus0x) {
6302 // C++03 [class.friend]p2:
6303 // An elaborated-type-specifier shall be used in a friend declaration
6304 // for a class.*
6305 //
6306 // * The class-key of the elaborated-type-specifier is required.
6307 if (!ActiveTemplateInstantiations.empty()) {
6308 // Do not complain about the form of friend template types during
6309 // template instantiation; we will already have complained when the
6310 // template was declared.
6311 } else if (!T->isElaboratedTypeSpecifier()) {
6312 // If we evaluated the type to a record type, suggest putting
6313 // a tag in front.
6314 if (const RecordType *RT = T->getAs<RecordType>()) {
6315 RecordDecl *RD = RT->getDecl();
6316
6317 std::string InsertionText = std::string(" ") + RD->getKindName();
6318
6319 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6320 << (unsigned) RD->getTagKind()
6321 << T
6322 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6323 InsertionText);
6324 } else {
6325 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6326 << T
6327 << SourceRange(FriendLoc, TypeRange.getEnd());
6328 }
6329 } else if (T->getAs<EnumType>()) {
6330 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006331 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006332 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006333 }
6334 }
6335
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006336 // C++0x [class.friend]p3:
6337 // If the type specifier in a friend declaration designates a (possibly
6338 // cv-qualified) class type, that class is declared as a friend; otherwise,
6339 // the friend declaration is ignored.
6340
6341 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6342 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006343
6344 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6345}
6346
John McCallace48cd2010-10-19 01:40:49 +00006347/// Handle a friend tag declaration where the scope specifier was
6348/// templated.
6349Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6350 unsigned TagSpec, SourceLocation TagLoc,
6351 CXXScopeSpec &SS,
6352 IdentifierInfo *Name, SourceLocation NameLoc,
6353 AttributeList *Attr,
6354 MultiTemplateParamsArg TempParamLists) {
6355 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6356
6357 bool isExplicitSpecialization = false;
6358 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6359 bool Invalid = false;
6360
6361 if (TemplateParameterList *TemplateParams
6362 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6363 TempParamLists.get(),
6364 TempParamLists.size(),
6365 /*friend*/ true,
6366 isExplicitSpecialization,
6367 Invalid)) {
6368 --NumMatchedTemplateParamLists;
6369
6370 if (TemplateParams->size() > 0) {
6371 // This is a declaration of a class template.
6372 if (Invalid)
6373 return 0;
6374
6375 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6376 SS, Name, NameLoc, Attr,
6377 TemplateParams, AS_public).take();
6378 } else {
6379 // The "template<>" header is extraneous.
6380 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6381 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6382 isExplicitSpecialization = true;
6383 }
6384 }
6385
6386 if (Invalid) return 0;
6387
6388 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6389
6390 bool isAllExplicitSpecializations = true;
6391 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6392 if (TempParamLists.get()[I]->size()) {
6393 isAllExplicitSpecializations = false;
6394 break;
6395 }
6396 }
6397
6398 // FIXME: don't ignore attributes.
6399
6400 // If it's explicit specializations all the way down, just forget
6401 // about the template header and build an appropriate non-templated
6402 // friend. TODO: for source fidelity, remember the headers.
6403 if (isAllExplicitSpecializations) {
6404 ElaboratedTypeKeyword Keyword
6405 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6406 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6407 TagLoc, SS.getRange(), NameLoc);
6408 if (T.isNull())
6409 return 0;
6410
6411 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6412 if (isa<DependentNameType>(T)) {
6413 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6414 TL.setKeywordLoc(TagLoc);
6415 TL.setQualifierRange(SS.getRange());
6416 TL.setNameLoc(NameLoc);
6417 } else {
6418 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6419 TL.setKeywordLoc(TagLoc);
6420 TL.setQualifierRange(SS.getRange());
6421 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6422 }
6423
6424 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6425 TSI, FriendLoc);
6426 Friend->setAccess(AS_public);
6427 CurContext->addDecl(Friend);
6428 return Friend;
6429 }
6430
6431 // Handle the case of a templated-scope friend class. e.g.
6432 // template <class T> class A<T>::B;
6433 // FIXME: we don't support these right now.
6434 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6435 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6436 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6437 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6438 TL.setKeywordLoc(TagLoc);
6439 TL.setQualifierRange(SS.getRange());
6440 TL.setNameLoc(NameLoc);
6441
6442 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6443 TSI, FriendLoc);
6444 Friend->setAccess(AS_public);
6445 Friend->setUnsupportedFriend(true);
6446 CurContext->addDecl(Friend);
6447 return Friend;
6448}
6449
6450
John McCall11083da2009-09-16 22:47:08 +00006451/// Handle a friend type declaration. This works in tandem with
6452/// ActOnTag.
6453///
6454/// Notes on friend class templates:
6455///
6456/// We generally treat friend class declarations as if they were
6457/// declaring a class. So, for example, the elaborated type specifier
6458/// in a friend declaration is required to obey the restrictions of a
6459/// class-head (i.e. no typedefs in the scope chain), template
6460/// parameters are required to match up with simple template-ids, &c.
6461/// However, unlike when declaring a template specialization, it's
6462/// okay to refer to a template specialization without an empty
6463/// template parameter declaration, e.g.
6464/// friend class A<T>::B<unsigned>;
6465/// We permit this as a special case; if there are any template
6466/// parameters present at all, require proper matching, i.e.
6467/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006468Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006469 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006470 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006471
6472 assert(DS.isFriendSpecified());
6473 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6474
John McCall11083da2009-09-16 22:47:08 +00006475 // Try to convert the decl specifier to a type. This works for
6476 // friend templates because ActOnTag never produces a ClassTemplateDecl
6477 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006478 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006479 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6480 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006481 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006482 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006483
Douglas Gregor6c110f32010-12-16 01:14:37 +00006484 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6485 return 0;
6486
John McCall11083da2009-09-16 22:47:08 +00006487 // This is definitely an error in C++98. It's probably meant to
6488 // be forbidden in C++0x, too, but the specification is just
6489 // poorly written.
6490 //
6491 // The problem is with declarations like the following:
6492 // template <T> friend A<T>::foo;
6493 // where deciding whether a class C is a friend or not now hinges
6494 // on whether there exists an instantiation of A that causes
6495 // 'foo' to equal C. There are restrictions on class-heads
6496 // (which we declare (by fiat) elaborated friend declarations to
6497 // be) that makes this tractable.
6498 //
6499 // FIXME: handle "template <> friend class A<T>;", which
6500 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006501 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006502 Diag(Loc, diag::err_tagless_friend_type_template)
6503 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006504 return 0;
John McCall11083da2009-09-16 22:47:08 +00006505 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006506
John McCallaa74a0c2009-08-28 07:59:38 +00006507 // C++98 [class.friend]p1: A friend of a class is a function
6508 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006509 // This is fixed in DR77, which just barely didn't make the C++03
6510 // deadline. It's also a very silly restriction that seriously
6511 // affects inner classes and which nobody else seems to implement;
6512 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006513 //
6514 // But note that we could warn about it: it's always useless to
6515 // friend one of your own members (it's not, however, worthless to
6516 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006517
John McCall11083da2009-09-16 22:47:08 +00006518 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006519 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006520 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006521 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006522 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006523 TSI,
John McCall11083da2009-09-16 22:47:08 +00006524 DS.getFriendSpecLoc());
6525 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006526 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6527
6528 if (!D)
John McCall48871652010-08-21 09:40:31 +00006529 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006530
John McCall11083da2009-09-16 22:47:08 +00006531 D->setAccess(AS_public);
6532 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006533
John McCall48871652010-08-21 09:40:31 +00006534 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006535}
6536
John McCallde3fd222010-10-12 23:13:28 +00006537Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6538 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006539 const DeclSpec &DS = D.getDeclSpec();
6540
6541 assert(DS.isFriendSpecified());
6542 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6543
6544 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006545 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6546 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006547
6548 // C++ [class.friend]p1
6549 // A friend of a class is a function or class....
6550 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006551 // It *doesn't* see through dependent types, which is correct
6552 // according to [temp.arg.type]p3:
6553 // If a declaration acquires a function type through a
6554 // type dependent on a template-parameter and this causes
6555 // a declaration that does not use the syntactic form of a
6556 // function declarator to have a function type, the program
6557 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006558 if (!T->isFunctionType()) {
6559 Diag(Loc, diag::err_unexpected_friend);
6560
6561 // It might be worthwhile to try to recover by creating an
6562 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006563 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006564 }
6565
6566 // C++ [namespace.memdef]p3
6567 // - If a friend declaration in a non-local class first declares a
6568 // class or function, the friend class or function is a member
6569 // of the innermost enclosing namespace.
6570 // - The name of the friend is not found by simple name lookup
6571 // until a matching declaration is provided in that namespace
6572 // scope (either before or after the class declaration granting
6573 // friendship).
6574 // - If a friend function is called, its name may be found by the
6575 // name lookup that considers functions from namespaces and
6576 // classes associated with the types of the function arguments.
6577 // - When looking for a prior declaration of a class or a function
6578 // declared as a friend, scopes outside the innermost enclosing
6579 // namespace scope are not considered.
6580
John McCallde3fd222010-10-12 23:13:28 +00006581 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006582 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6583 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006584 assert(Name);
6585
Douglas Gregor6c110f32010-12-16 01:14:37 +00006586 // Check for unexpanded parameter packs.
6587 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6588 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6589 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6590 return 0;
6591
John McCall07e91c02009-08-06 02:15:43 +00006592 // The context we found the declaration in, or in which we should
6593 // create the declaration.
6594 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006595 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006596 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006597 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006598
John McCallde3fd222010-10-12 23:13:28 +00006599 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006600
John McCallde3fd222010-10-12 23:13:28 +00006601 // There are four cases here.
6602 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006603 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006604 // there as appropriate.
6605 // Recover from invalid scope qualifiers as if they just weren't there.
6606 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006607 // C++0x [namespace.memdef]p3:
6608 // If the name in a friend declaration is neither qualified nor
6609 // a template-id and the declaration is a function or an
6610 // elaborated-type-specifier, the lookup to determine whether
6611 // the entity has been previously declared shall not consider
6612 // any scopes outside the innermost enclosing namespace.
6613 // C++0x [class.friend]p11:
6614 // If a friend declaration appears in a local class and the name
6615 // specified is an unqualified name, a prior declaration is
6616 // looked up without considering scopes that are outside the
6617 // innermost enclosing non-class scope. For a friend function
6618 // declaration, if there is no prior declaration, the program is
6619 // ill-formed.
6620 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006621 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006622
John McCallf7cfb222010-10-13 05:45:15 +00006623 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006624 DC = CurContext;
6625 while (true) {
6626 // Skip class contexts. If someone can cite chapter and verse
6627 // for this behavior, that would be nice --- it's what GCC and
6628 // EDG do, and it seems like a reasonable intent, but the spec
6629 // really only says that checks for unqualified existing
6630 // declarations should stop at the nearest enclosing namespace,
6631 // not that they should only consider the nearest enclosing
6632 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006633 while (DC->isRecord())
6634 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006635
John McCall1f82f242009-11-18 22:49:29 +00006636 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006637
6638 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006639 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006640 break;
John McCallf7cfb222010-10-13 05:45:15 +00006641
John McCallf4776592010-10-14 22:22:28 +00006642 if (isTemplateId) {
6643 if (isa<TranslationUnitDecl>(DC)) break;
6644 } else {
6645 if (DC->isFileContext()) break;
6646 }
John McCall07e91c02009-08-06 02:15:43 +00006647 DC = DC->getParent();
6648 }
6649
6650 // C++ [class.friend]p1: A friend of a class is a function or
6651 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006652 // C++0x changes this for both friend types and functions.
6653 // Most C++ 98 compilers do seem to give an error here, so
6654 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006655 if (!Previous.empty() && DC->Equals(CurContext)
6656 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006657 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006658
John McCallccbc0322010-10-13 06:22:15 +00006659 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006660
John McCallde3fd222010-10-12 23:13:28 +00006661 // - There's a non-dependent scope specifier, in which case we
6662 // compute it and do a previous lookup there for a function
6663 // or function template.
6664 } else if (!SS.getScopeRep()->isDependent()) {
6665 DC = computeDeclContext(SS);
6666 if (!DC) return 0;
6667
6668 if (RequireCompleteDeclContext(SS, DC)) return 0;
6669
6670 LookupQualifiedName(Previous, DC);
6671
6672 // Ignore things found implicitly in the wrong scope.
6673 // TODO: better diagnostics for this case. Suggesting the right
6674 // qualified scope would be nice...
6675 LookupResult::Filter F = Previous.makeFilter();
6676 while (F.hasNext()) {
6677 NamedDecl *D = F.next();
6678 if (!DC->InEnclosingNamespaceSetOf(
6679 D->getDeclContext()->getRedeclContext()))
6680 F.erase();
6681 }
6682 F.done();
6683
6684 if (Previous.empty()) {
6685 D.setInvalidType();
6686 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6687 return 0;
6688 }
6689
6690 // C++ [class.friend]p1: A friend of a class is a function or
6691 // class that is not a member of the class . . .
6692 if (DC->Equals(CurContext))
6693 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6694
6695 // - There's a scope specifier that does not match any template
6696 // parameter lists, in which case we use some arbitrary context,
6697 // create a method or method template, and wait for instantiation.
6698 // - There's a scope specifier that does match some template
6699 // parameter lists, which we don't handle right now.
6700 } else {
6701 DC = CurContext;
6702 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006703 }
6704
John McCallf7cfb222010-10-13 05:45:15 +00006705 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006706 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006707 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6708 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6709 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006710 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006711 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6712 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006713 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006714 }
John McCall07e91c02009-08-06 02:15:43 +00006715 }
6716
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006717 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006718 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006719 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006720 IsDefinition,
6721 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006722 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006723
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006724 assert(ND->getDeclContext() == DC);
6725 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006726
John McCall759e32b2009-08-31 22:39:49 +00006727 // Add the function declaration to the appropriate lookup tables,
6728 // adjusting the redeclarations list as necessary. We don't
6729 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006730 //
John McCall759e32b2009-08-31 22:39:49 +00006731 // Also update the scope-based lookup if the target context's
6732 // lookup context is in lexical scope.
6733 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006734 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006735 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006736 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006737 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006738 }
John McCallaa74a0c2009-08-28 07:59:38 +00006739
6740 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006741 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006742 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006743 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006744 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006745
John McCallde3fd222010-10-12 23:13:28 +00006746 if (ND->isInvalidDecl())
6747 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006748 else {
6749 FunctionDecl *FD;
6750 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6751 FD = FTD->getTemplatedDecl();
6752 else
6753 FD = cast<FunctionDecl>(ND);
6754
6755 // Mark templated-scope function declarations as unsupported.
6756 if (FD->getNumTemplateParameterLists())
6757 FrD->setUnsupportedFriend(true);
6758 }
John McCallde3fd222010-10-12 23:13:28 +00006759
John McCall48871652010-08-21 09:40:31 +00006760 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006761}
6762
John McCall48871652010-08-21 09:40:31 +00006763void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6764 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006765
Sebastian Redlf769df52009-03-24 22:27:57 +00006766 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6767 if (!Fn) {
6768 Diag(DelLoc, diag::err_deleted_non_function);
6769 return;
6770 }
6771 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6772 Diag(DelLoc, diag::err_deleted_decl_not_first);
6773 Diag(Prev->getLocation(), diag::note_previous_declaration);
6774 // If the declaration wasn't the first, we delete the function anyway for
6775 // recovery.
6776 }
6777 Fn->setDeleted();
6778}
Sebastian Redl4c018662009-04-27 21:33:24 +00006779
6780static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6781 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6782 ++CI) {
6783 Stmt *SubStmt = *CI;
6784 if (!SubStmt)
6785 continue;
6786 if (isa<ReturnStmt>(SubStmt))
6787 Self.Diag(SubStmt->getSourceRange().getBegin(),
6788 diag::err_return_in_constructor_handler);
6789 if (!isa<Expr>(SubStmt))
6790 SearchForReturnInStmt(Self, SubStmt);
6791 }
6792}
6793
6794void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6795 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6796 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6797 SearchForReturnInStmt(*this, Handler);
6798 }
6799}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006800
Mike Stump11289f42009-09-09 15:08:12 +00006801bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006802 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006803 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6804 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006805
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006806 if (Context.hasSameType(NewTy, OldTy) ||
6807 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006808 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006809
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006810 // Check if the return types are covariant
6811 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006812
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006813 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006814 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6815 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006816 NewClassTy = NewPT->getPointeeType();
6817 OldClassTy = OldPT->getPointeeType();
6818 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006819 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6820 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6821 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6822 NewClassTy = NewRT->getPointeeType();
6823 OldClassTy = OldRT->getPointeeType();
6824 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006825 }
6826 }
Mike Stump11289f42009-09-09 15:08:12 +00006827
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006828 // The return types aren't either both pointers or references to a class type.
6829 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006830 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006831 diag::err_different_return_type_for_overriding_virtual_function)
6832 << New->getDeclName() << NewTy << OldTy;
6833 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006834
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006835 return true;
6836 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006837
Anders Carlssone60365b2009-12-31 18:34:24 +00006838 // C++ [class.virtual]p6:
6839 // If the return type of D::f differs from the return type of B::f, the
6840 // class type in the return type of D::f shall be complete at the point of
6841 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006842 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6843 if (!RT->isBeingDefined() &&
6844 RequireCompleteType(New->getLocation(), NewClassTy,
6845 PDiag(diag::err_covariant_return_incomplete)
6846 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006847 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006848 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006849
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006850 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006851 // Check if the new class derives from the old class.
6852 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6853 Diag(New->getLocation(),
6854 diag::err_covariant_return_not_derived)
6855 << New->getDeclName() << NewTy << OldTy;
6856 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6857 return true;
6858 }
Mike Stump11289f42009-09-09 15:08:12 +00006859
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006860 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006861 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006862 diag::err_covariant_return_inaccessible_base,
6863 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6864 // FIXME: Should this point to the return type?
6865 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006866 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6867 return true;
6868 }
6869 }
Mike Stump11289f42009-09-09 15:08:12 +00006870
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006871 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006872 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006873 Diag(New->getLocation(),
6874 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006875 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006876 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6877 return true;
6878 };
Mike Stump11289f42009-09-09 15:08:12 +00006879
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006880
6881 // The new class type must have the same or less qualifiers as the old type.
6882 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6883 Diag(New->getLocation(),
6884 diag::err_covariant_return_type_class_type_more_qualified)
6885 << New->getDeclName() << NewTy << OldTy;
6886 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6887 return true;
6888 };
Mike Stump11289f42009-09-09 15:08:12 +00006889
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006890 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006891}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006892
Alexis Hunt96d5c762009-11-21 08:43:09 +00006893bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6894 const CXXMethodDecl *Old)
6895{
6896 if (Old->hasAttr<FinalAttr>()) {
6897 Diag(New->getLocation(), diag::err_final_function_overridden)
6898 << New->getDeclName();
6899 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6900 return true;
6901 }
6902
6903 return false;
6904}
6905
Douglas Gregor21920e372009-12-01 17:24:26 +00006906/// \brief Mark the given method pure.
6907///
6908/// \param Method the method to be marked pure.
6909///
6910/// \param InitRange the source range that covers the "0" initializer.
6911bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6912 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6913 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006914 return false;
6915 }
6916
6917 if (!Method->isInvalidDecl())
6918 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6919 << Method->getDeclName() << InitRange;
6920 return true;
6921}
6922
John McCall1f4ee7b2009-12-19 09:28:58 +00006923/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6924/// an initializer for the out-of-line declaration 'Dcl'. The scope
6925/// is a fresh scope pushed for just this purpose.
6926///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006927/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6928/// static data member of class X, names should be looked up in the scope of
6929/// class X.
John McCall48871652010-08-21 09:40:31 +00006930void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006931 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006932 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006933
John McCall1f4ee7b2009-12-19 09:28:58 +00006934 // We should only get called for declarations with scope specifiers, like:
6935 // int foo::bar;
6936 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006937 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006938}
6939
6940/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006941/// initializer for the out-of-line declaration 'D'.
6942void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006943 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006944 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006945
John McCall1f4ee7b2009-12-19 09:28:58 +00006946 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006947 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006948}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006949
6950/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6951/// C++ if/switch/while/for statement.
6952/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006953DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006954 // C++ 6.4p2:
6955 // The declarator shall not specify a function or an array.
6956 // The type-specifier-seq shall not contain typedef and shall not declare a
6957 // new class or enumeration.
6958 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6959 "Parser allowed 'typedef' as storage class of condition decl.");
6960
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006961 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006962 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6963 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006964
6965 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6966 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6967 // would be created and CXXConditionDeclExpr wants a VarDecl.
6968 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6969 << D.getSourceRange();
6970 return DeclResult();
6971 } else if (OwnedTag && OwnedTag->isDefinition()) {
6972 // The type-specifier-seq shall not declare a new class or enumeration.
6973 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6974 }
6975
John McCall48871652010-08-21 09:40:31 +00006976 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006977 if (!Dcl)
6978 return DeclResult();
6979
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006980 return Dcl;
6981}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006982
Douglas Gregor88d292c2010-05-13 16:44:06 +00006983void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6984 bool DefinitionRequired) {
6985 // Ignore any vtable uses in unevaluated operands or for classes that do
6986 // not have a vtable.
6987 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6988 CurContext->isDependentContext() ||
6989 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006990 return;
6991
Douglas Gregor88d292c2010-05-13 16:44:06 +00006992 // Try to insert this class into the map.
6993 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6994 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6995 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6996 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006997 // If we already had an entry, check to see if we are promoting this vtable
6998 // to required a definition. If so, we need to reappend to the VTableUses
6999 // list, since we may have already processed the first entry.
7000 if (DefinitionRequired && !Pos.first->second) {
7001 Pos.first->second = true;
7002 } else {
7003 // Otherwise, we can early exit.
7004 return;
7005 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007006 }
7007
7008 // Local classes need to have their virtual members marked
7009 // immediately. For all other classes, we mark their virtual members
7010 // at the end of the translation unit.
7011 if (Class->isLocalClass())
7012 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007013 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007014 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007015}
7016
Douglas Gregor88d292c2010-05-13 16:44:06 +00007017bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007018 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007019 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007020
Douglas Gregor88d292c2010-05-13 16:44:06 +00007021 // Note: The VTableUses vector could grow as a result of marking
7022 // the members of a class as "used", so we check the size each
7023 // time through the loop and prefer indices (with are stable) to
7024 // iterators (which are not).
7025 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007026 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007027 if (!Class)
7028 continue;
7029
7030 SourceLocation Loc = VTableUses[I].second;
7031
7032 // If this class has a key function, but that key function is
7033 // defined in another translation unit, we don't need to emit the
7034 // vtable even though we're using it.
7035 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007036 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007037 switch (KeyFunction->getTemplateSpecializationKind()) {
7038 case TSK_Undeclared:
7039 case TSK_ExplicitSpecialization:
7040 case TSK_ExplicitInstantiationDeclaration:
7041 // The key function is in another translation unit.
7042 continue;
7043
7044 case TSK_ExplicitInstantiationDefinition:
7045 case TSK_ImplicitInstantiation:
7046 // We will be instantiating the key function.
7047 break;
7048 }
7049 } else if (!KeyFunction) {
7050 // If we have a class with no key function that is the subject
7051 // of an explicit instantiation declaration, suppress the
7052 // vtable; it will live with the explicit instantiation
7053 // definition.
7054 bool IsExplicitInstantiationDeclaration
7055 = Class->getTemplateSpecializationKind()
7056 == TSK_ExplicitInstantiationDeclaration;
7057 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7058 REnd = Class->redecls_end();
7059 R != REnd; ++R) {
7060 TemplateSpecializationKind TSK
7061 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7062 if (TSK == TSK_ExplicitInstantiationDeclaration)
7063 IsExplicitInstantiationDeclaration = true;
7064 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7065 IsExplicitInstantiationDeclaration = false;
7066 break;
7067 }
7068 }
7069
7070 if (IsExplicitInstantiationDeclaration)
7071 continue;
7072 }
7073
7074 // Mark all of the virtual members of this class as referenced, so
7075 // that we can build a vtable. Then, tell the AST consumer that a
7076 // vtable for this class is required.
7077 MarkVirtualMembersReferenced(Loc, Class);
7078 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7079 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7080
7081 // Optionally warn if we're emitting a weak vtable.
7082 if (Class->getLinkage() == ExternalLinkage &&
7083 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007084 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007085 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7086 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007087 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007088 VTableUses.clear();
7089
Anders Carlsson82fccd02009-12-07 08:24:59 +00007090 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007091}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007092
Rafael Espindola5b334082010-03-26 00:36:59 +00007093void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7094 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007095 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7096 e = RD->method_end(); i != e; ++i) {
7097 CXXMethodDecl *MD = *i;
7098
7099 // C++ [basic.def.odr]p2:
7100 // [...] A virtual member function is used if it is not pure. [...]
7101 if (MD->isVirtual() && !MD->isPure())
7102 MarkDeclarationReferenced(Loc, MD);
7103 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007104
7105 // Only classes that have virtual bases need a VTT.
7106 if (RD->getNumVBases() == 0)
7107 return;
7108
7109 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7110 e = RD->bases_end(); i != e; ++i) {
7111 const CXXRecordDecl *Base =
7112 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007113 if (Base->getNumVBases() == 0)
7114 continue;
7115 MarkVirtualMembersReferenced(Loc, Base);
7116 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007117}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007118
7119/// SetIvarInitializers - This routine builds initialization ASTs for the
7120/// Objective-C implementation whose ivars need be initialized.
7121void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7122 if (!getLangOptions().CPlusPlus)
7123 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007124 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007125 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7126 CollectIvarsToConstructOrDestruct(OID, ivars);
7127 if (ivars.empty())
7128 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007129 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007130 for (unsigned i = 0; i < ivars.size(); i++) {
7131 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007132 if (Field->isInvalidDecl())
7133 continue;
7134
Alexis Hunt1d792652011-01-08 20:30:50 +00007135 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007136 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7137 InitializationKind InitKind =
7138 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7139
7140 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007141 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007142 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007143 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007144 // Note, MemberInit could actually come back empty if no initialization
7145 // is required (e.g., because it would call a trivial default constructor)
7146 if (!MemberInit.get() || MemberInit.isInvalid())
7147 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007148
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007149 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007150 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7151 SourceLocation(),
7152 MemberInit.takeAs<Expr>(),
7153 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007154 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007155
7156 // Be sure that the destructor is accessible and is marked as referenced.
7157 if (const RecordType *RecordTy
7158 = Context.getBaseElementType(Field->getType())
7159 ->getAs<RecordType>()) {
7160 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007161 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007162 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7163 CheckDestructorAccess(Field->getLocation(), Destructor,
7164 PDiag(diag::err_access_dtor_ivar)
7165 << Context.getBaseElementType(Field->getType()));
7166 }
7167 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007168 }
7169 ObjCImplementation->setIvarInitializers(Context,
7170 AllToInit.data(), AllToInit.size());
7171 }
7172}