blob: b33261e4ea1e3b4b877790710e27fb5de97f8554 [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,
John McCall37ad5512010-08-23 06:44:23 +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);
Anders Carlsson6e997b22009-12-15 20:51:39 +0000140 Arg = MaybeCreateCXXExprWithTemporaries(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
Anders Carlssonf1c26952009-08-25 01:02:06 +0000180 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000181 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
182 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000183 Param->setInvalidDecl();
184 return;
185 }
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCallb268a282010-08-23 23:25:46 +0000187 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000188}
189
Douglas Gregor58354032008-12-24 00:01:03 +0000190/// ActOnParamUnparsedDefaultArgument - We've seen a default
191/// argument for a function parameter, but we can't parse it yet
192/// because we're inside a class definition. Note that this default
193/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000194void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000195 SourceLocation EqualLoc,
196 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump11289f42009-09-09 15:08:12 +0000199
John McCall48871652010-08-21 09:40:31 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000201 if (Param)
202 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000205}
206
Douglas Gregor4d87df52008-12-16 21:30:33 +0000207/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
208/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000209void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000210 if (!param)
211 return;
Mike Stump11289f42009-09-09 15:08:12 +0000212
John McCall48871652010-08-21 09:40:31 +0000213 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000214
Anders Carlsson84613c42009-06-12 16:51:40 +0000215 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000216
Anders Carlsson84613c42009-06-12 16:51:40 +0000217 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000218}
219
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000220/// CheckExtraCXXDefaultArguments - Check for any extra default
221/// arguments in the declarator, which is not a function declaration
222/// or definition and therefore is not permitted to have default
223/// arguments. This routine should be invoked for every declarator
224/// that is not a function declaration or definition.
225void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
226 // C++ [dcl.fct.default]p3
227 // A default argument expression shall be specified only in the
228 // parameter-declaration-clause of a function declaration or in a
229 // template-parameter (14.1). It shall not be specified for a
230 // parameter pack. If it is specified in a
231 // parameter-declaration-clause, it shall not occur within a
232 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000234 DeclaratorChunk &chunk = D.getTypeObject(i);
235 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000236 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
237 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000238 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000239 if (Param->hasUnparsedDefaultArg()) {
240 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000241 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
242 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
243 delete Toks;
244 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000245 } else if (Param->getDefaultArg()) {
246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << Param->getDefaultArg()->getSourceRange();
248 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000249 }
250 }
251 }
252 }
253}
254
Chris Lattner199abbc2008-04-08 05:04:30 +0000255// MergeCXXFunctionDecl - Merge two declarations of the same C++
256// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000257// type. Subroutine of MergeFunctionDecl. Returns true if there was an
258// error, false otherwise.
259bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
260 bool Invalid = false;
261
Chris Lattner199abbc2008-04-08 05:04:30 +0000262 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000263 // For non-template functions, default arguments can be added in
264 // later declarations of a function in the same
265 // scope. Declarations in different scopes have completely
266 // distinct sets of default arguments. That is, declarations in
267 // inner scopes do not acquire default arguments from
268 // declarations in outer scopes, and vice versa. In a given
269 // function declaration, all parameters subsequent to a
270 // parameter with a default argument shall have default
271 // arguments supplied in this or previous declarations. A
272 // default argument shall not be redefined by a later
273 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000274 //
275 // C++ [dcl.fct.default]p6:
276 // Except for member functions of class templates, the default arguments
277 // in a member function definition that appears outside of the class
278 // definition are added to the set of default arguments provided by the
279 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000280 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
281 ParmVarDecl *OldParam = Old->getParamDecl(p);
282 ParmVarDecl *NewParam = New->getParamDecl(p);
283
Douglas Gregorc732aba2009-09-11 18:44:32 +0000284 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000285 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
286 // hint here. Alternatively, we could walk the type-source information
287 // for NewParam to find the last source location in the type... but it
288 // isn't worth the effort right now. This is the kind of test case that
289 // is hard to get right:
290
291 // int f(int);
292 // void g(int (*fp)(int) = f);
293 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000294 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000295 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000296 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000297
298 // Look for the function declaration where the default argument was
299 // actually written, which may be a declaration prior to Old.
300 for (FunctionDecl *Older = Old->getPreviousDeclaration();
301 Older; Older = Older->getPreviousDeclaration()) {
302 if (!Older->getParamDecl(p)->hasDefaultArg())
303 break;
304
305 OldParam = Older->getParamDecl(p);
306 }
307
308 Diag(OldParam->getLocation(), diag::note_previous_definition)
309 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000310 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000311 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000312 // Merge the old default argument into the new parameter.
313 // It's important to use getInit() here; getDefaultArg()
314 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000315 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000316 if (OldParam->hasUninstantiatedDefaultArg())
317 NewParam->setUninstantiatedDefaultArg(
318 OldParam->getUninstantiatedDefaultArg());
319 else
John McCalle61b02b2010-05-04 01:53:42 +0000320 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000321 } else if (NewParam->hasDefaultArg()) {
322 if (New->getDescribedFunctionTemplate()) {
323 // Paragraph 4, quoted above, only applies to non-template functions.
324 Diag(NewParam->getLocation(),
325 diag::err_param_default_argument_template_redecl)
326 << NewParam->getDefaultArgRange();
327 Diag(Old->getLocation(), diag::note_template_prev_declaration)
328 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000329 } else if (New->getTemplateSpecializationKind()
330 != TSK_ImplicitInstantiation &&
331 New->getTemplateSpecializationKind() != TSK_Undeclared) {
332 // C++ [temp.expr.spec]p21:
333 // Default function arguments shall not be specified in a declaration
334 // or a definition for one of the following explicit specializations:
335 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000336 // - the explicit specialization of a member function template;
337 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000338 // template where the class template specialization to which the
339 // member function specialization belongs is implicitly
340 // instantiated.
341 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
342 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
343 << New->getDeclName()
344 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000345 } else if (New->getDeclContext()->isDependentContext()) {
346 // C++ [dcl.fct.default]p6 (DR217):
347 // Default arguments for a member function of a class template shall
348 // be specified on the initial declaration of the member function
349 // within the class template.
350 //
351 // Reading the tea leaves a bit in DR217 and its reference to DR205
352 // leads me to the conclusion that one cannot add default function
353 // arguments for an out-of-line definition of a member function of a
354 // dependent type.
355 int WhichKind = 2;
356 if (CXXRecordDecl *Record
357 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
358 if (Record->getDescribedClassTemplate())
359 WhichKind = 0;
360 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
361 WhichKind = 1;
362 else
363 WhichKind = 2;
364 }
365
366 Diag(NewParam->getLocation(),
367 diag::err_param_default_argument_member_template_redecl)
368 << WhichKind
369 << NewParam->getDefaultArgRange();
370 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000371 }
372 }
373
Douglas Gregorf40863c2010-02-12 07:32:17 +0000374 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000375 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000376
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000377 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000378}
379
380/// CheckCXXDefaultArguments - Verify that the default arguments for a
381/// function declaration are well-formed according to C++
382/// [dcl.fct.default].
383void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
384 unsigned NumParams = FD->getNumParams();
385 unsigned p;
386
387 // Find first parameter with a default argument
388 for (p = 0; p < NumParams; ++p) {
389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000390 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000391 break;
392 }
393
394 // C++ [dcl.fct.default]p4:
395 // In a given function declaration, all parameters
396 // subsequent to a parameter with a default argument shall
397 // have default arguments supplied in this or previous
398 // declarations. A default argument shall not be redefined
399 // by a later declaration (not even to the same value).
400 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000401 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000402 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000403 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000404 if (Param->isInvalidDecl())
405 /* We already complained about this parameter. */;
406 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000407 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000408 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000409 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000410 else
Mike Stump11289f42009-09-09 15:08:12 +0000411 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000412 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner199abbc2008-04-08 05:04:30 +0000414 LastMissingDefaultArg = p;
415 }
416 }
417
418 if (LastMissingDefaultArg > 0) {
419 // Some default arguments were missing. Clear out all of the
420 // default arguments up to (and including) the last missing
421 // default argument, so that we leave the function parameters
422 // in a semantically valid state.
423 for (p = 0; p <= LastMissingDefaultArg; ++p) {
424 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000425 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000426 Param->setDefaultArg(0);
427 }
428 }
429 }
430}
Douglas Gregor556877c2008-04-13 21:30:24 +0000431
Douglas Gregor61956c42008-10-31 09:07:45 +0000432/// isCurrentClassName - Determine whether the identifier II is the
433/// name of the class type currently being defined. In the case of
434/// nested classes, this will only return true if II is the name of
435/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000436bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
437 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000438 assert(getLangOptions().CPlusPlus && "No class names in C!");
439
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000440 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000441 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000442 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000443 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
444 } else
445 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
446
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000447 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000448 return &II == CurDecl->getIdentifier();
449 else
450 return false;
451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000454///
455/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
456/// and returns NULL otherwise.
457CXXBaseSpecifier *
458Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
459 SourceRange SpecifierRange,
460 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000461 TypeSourceInfo *TInfo) {
462 QualType BaseType = TInfo->getType();
463
Douglas Gregor463421d2009-03-03 04:44:36 +0000464 // C++ [class.union]p1:
465 // A union shall not have base classes.
466 if (Class->isUnion()) {
467 Diag(Class->getLocation(), diag::err_base_clause_on_union)
468 << SpecifierRange;
469 return 0;
470 }
471
472 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000473 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000474 Class->getTagKind() == TTK_Class,
475 Access, TInfo);
476
477 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000478
479 // Base specifiers must be record types.
480 if (!BaseType->isRecordType()) {
481 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
482 return 0;
483 }
484
485 // C++ [class.union]p1:
486 // A union shall not be used as a base class.
487 if (BaseType->isUnionType()) {
488 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
489 return 0;
490 }
491
492 // C++ [class.derived]p2:
493 // The class-name in a base-specifier shall not be an incompletely
494 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000495 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000496 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000497 << SpecifierRange)) {
498 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000499 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000500 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000501
Eli Friedmanc96d4962009-08-15 21:55:26 +0000502 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000503 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000504 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000505 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000506 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000507 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
508 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000509
Alexis Hunt96d5c762009-11-21 08:43:09 +0000510 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
511 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
512 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000513 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
514 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000515 return 0;
516 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000517
John McCall3696dcb2010-08-17 07:23:57 +0000518 if (BaseDecl->isInvalidDecl())
519 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000520
521 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000522 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000523 Class->getTagKind() == TTK_Class,
524 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000525}
526
Douglas Gregor556877c2008-04-13 21:30:24 +0000527/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
528/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000529/// example:
530/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000531/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000532BaseResult
John McCall48871652010-08-21 09:40:31 +0000533Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000534 bool Virtual, AccessSpecifier Access,
John McCallba7bf592010-08-24 05:47:05 +0000535 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000536 if (!classdecl)
537 return true;
538
Douglas Gregorc40290e2009-03-09 23:48:35 +0000539 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000541 if (!Class)
542 return true;
543
Nick Lewycky19b9f952010-07-26 16:56:01 +0000544 TypeSourceInfo *TInfo = 0;
545 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor463421d2009-03-03 04:44:36 +0000546 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000547 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000548 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Douglas Gregor463421d2009-03-03 04:44:36 +0000550 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000551}
Douglas Gregor556877c2008-04-13 21:30:24 +0000552
Douglas Gregor463421d2009-03-03 04:44:36 +0000553/// \brief Performs the actual work of attaching the given base class
554/// specifiers to a C++ class.
555bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
556 unsigned NumBases) {
557 if (NumBases == 0)
558 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000559
560 // Used to keep track of which base types we have already seen, so
561 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000562 // that the key is always the unqualified canonical type of the base
563 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000564 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
565
566 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000567 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000569 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000570 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000572 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000573 if (!Class->hasObjectMember()) {
574 if (const RecordType *FDTTy =
575 NewBaseType.getTypePtr()->getAs<RecordType>())
576 if (FDTTy->getDecl()->hasObjectMember())
577 Class->setHasObjectMember(true);
578 }
579
Douglas Gregor29a92472008-10-22 17:49:05 +0000580 if (KnownBaseTypes[NewBaseType]) {
581 // C++ [class.mi]p3:
582 // A class shall not be specified as a direct base class of a
583 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000584 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000585 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000586 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000587 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000588
589 // Delete the duplicate base class specifier; we're going to
590 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000591 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000592
593 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000594 } else {
595 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 KnownBaseTypes[NewBaseType] = Bases[idx];
597 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000598 }
599 }
600
601 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000602 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000603
604 // Delete the remaining (good) base class specifiers, since their
605 // data has been copied into the CXXRecordDecl.
606 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000607 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000608
609 return Invalid;
610}
611
612/// ActOnBaseSpecifiers - Attach the given base specifiers to the
613/// class, after checking whether there are any duplicate base
614/// classes.
John McCall48871652010-08-21 09:40:31 +0000615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000616 unsigned NumBases) {
617 if (!ClassDecl || !Bases || !NumBases)
618 return;
619
620 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000623}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000624
John McCalle78aac42010-03-10 03:28:59 +0000625static CXXRecordDecl *GetClassForType(QualType T) {
626 if (const RecordType *RT = T->getAs<RecordType>())
627 return cast<CXXRecordDecl>(RT->getDecl());
628 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
629 return ICT->getDecl();
630 else
631 return 0;
632}
633
Douglas Gregor36d1b142009-10-06 17:59:45 +0000634/// \brief Determine whether the type \p Derived is a C++ class that is
635/// derived from the type \p Base.
636bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
637 if (!getLangOptions().CPlusPlus)
638 return false;
John McCalle78aac42010-03-10 03:28:59 +0000639
640 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
641 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000642 return false;
643
John McCalle78aac42010-03-10 03:28:59 +0000644 CXXRecordDecl *BaseRD = GetClassForType(Base);
645 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000646 return false;
647
John McCall67da35c2010-02-04 22:26:26 +0000648 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
649 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000650}
651
652/// \brief Determine whether the type \p Derived is a C++ class that is
653/// derived from the type \p Base.
654bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
655 if (!getLangOptions().CPlusPlus)
656 return false;
657
John McCalle78aac42010-03-10 03:28:59 +0000658 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
659 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000660 return false;
661
John McCalle78aac42010-03-10 03:28:59 +0000662 CXXRecordDecl *BaseRD = GetClassForType(Base);
663 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
Douglas Gregor36d1b142009-10-06 17:59:45 +0000666 return DerivedRD->isDerivedFrom(BaseRD, Paths);
667}
668
Anders Carlssona70cff62010-04-24 19:06:50 +0000669void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000670 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000671 assert(BasePathArray.empty() && "Base path array must be empty!");
672 assert(Paths.isRecordingPaths() && "Must record paths!");
673
674 const CXXBasePath &Path = Paths.front();
675
676 // We first go backward and check if we have a virtual base.
677 // FIXME: It would be better if CXXBasePath had the base specifier for
678 // the nearest virtual base.
679 unsigned Start = 0;
680 for (unsigned I = Path.size(); I != 0; --I) {
681 if (Path[I - 1].Base->isVirtual()) {
682 Start = I - 1;
683 break;
684 }
685 }
686
687 // Now add all bases.
688 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000690}
691
Douglas Gregor88d292c2010-05-13 16:44:06 +0000692/// \brief Determine whether the given base path includes a virtual
693/// base class.
John McCallcf142162010-08-07 06:22:56 +0000694bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
695 for (CXXCastPath::const_iterator B = BasePath.begin(),
696 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000697 B != BEnd; ++B)
698 if ((*B)->isVirtual())
699 return true;
700
701 return false;
702}
703
Douglas Gregor36d1b142009-10-06 17:59:45 +0000704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
705/// conversion (where Derived and Base are class types) is
706/// well-formed, meaning that the conversion is unambiguous (and
707/// that all of the base classes are accessible). Returns true
708/// and emits a diagnostic if the code is ill-formed, returns false
709/// otherwise. Loc is the location where this routine should point to
710/// if there is an error, and Range is the source range to highlight
711/// if there is an error.
712bool
713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000714 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000715 unsigned AmbigiousBaseConvID,
716 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000717 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000718 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000719 // First, determine whether the path from Derived to Base is
720 // ambiguous. This is slightly more expensive than checking whether
721 // the Derived to Base conversion exists, because here we need to
722 // explore multiple paths to determine if there is an ambiguity.
723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
724 /*DetectVirtual=*/false);
725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
726 assert(DerivationOkay &&
727 "Can only be used with a derived-to-base conversion");
728 (void)DerivationOkay;
729
730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000731 if (InaccessibleBaseID) {
732 // Check that the base class can be accessed.
733 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
734 InaccessibleBaseID)) {
735 case AR_inaccessible:
736 return true;
737 case AR_accessible:
738 case AR_dependent:
739 case AR_delayed:
740 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000741 }
John McCall5b0829a2010-02-10 09:31:12 +0000742 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000743
744 // Build a base path if necessary.
745 if (BasePath)
746 BuildBasePathArray(Paths, *BasePath);
747 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000748 }
749
750 // We know that the derived-to-base conversion is ambiguous, and
751 // we're going to produce a diagnostic. Perform the derived-to-base
752 // search just one more time to compute all of the possible paths so
753 // that we can print them out. This is more expensive than any of
754 // the previous derived-to-base checks we've done, but at this point
755 // performance isn't as much of an issue.
756 Paths.clear();
757 Paths.setRecordingPaths(true);
758 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
759 assert(StillOkay && "Can only be used with a derived-to-base conversion");
760 (void)StillOkay;
761
762 // Build up a textual representation of the ambiguous paths, e.g.,
763 // D -> B -> A, that will be used to illustrate the ambiguous
764 // conversions in the diagnostic. We only print one of the paths
765 // to each base class subobject.
766 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
767
768 Diag(Loc, AmbigiousBaseConvID)
769 << Derived << Base << PathDisplayStr << Range << Name;
770 return true;
771}
772
773bool
774Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000775 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000776 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000777 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000778 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000779 IgnoreAccess ? 0
780 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000781 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000782 Loc, Range, DeclarationName(),
783 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000784}
785
786
787/// @brief Builds a string representing ambiguous paths from a
788/// specific derived class to different subobjects of the same base
789/// class.
790///
791/// This function builds a string that can be used in error messages
792/// to show the different paths that one can take through the
793/// inheritance hierarchy to go from the derived class to different
794/// subobjects of a base class. The result looks something like this:
795/// @code
796/// struct D -> struct B -> struct A
797/// struct D -> struct C -> struct A
798/// @endcode
799std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
800 std::string PathDisplayStr;
801 std::set<unsigned> DisplayedPaths;
802 for (CXXBasePaths::paths_iterator Path = Paths.begin();
803 Path != Paths.end(); ++Path) {
804 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
805 // We haven't displayed a path to this particular base
806 // class subobject yet.
807 PathDisplayStr += "\n ";
808 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
809 for (CXXBasePath::const_iterator Element = Path->begin();
810 Element != Path->end(); ++Element)
811 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
812 }
813 }
814
815 return PathDisplayStr;
816}
817
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000818//===----------------------------------------------------------------------===//
819// C++ class member Handling
820//===----------------------------------------------------------------------===//
821
Abramo Bagnarad7340582010-06-05 05:09:32 +0000822/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000823Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
824 SourceLocation ASLoc,
825 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000826 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000827 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000828 ASLoc, ColonLoc);
829 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000830 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000831}
832
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000833/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
834/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
835/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000836/// any.
John McCall48871652010-08-21 09:40:31 +0000837Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000838Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000839 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000840 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
841 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000842 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000843 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
844 DeclarationName Name = NameInfo.getName();
845 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000846 Expr *BitWidth = static_cast<Expr*>(BW);
847 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000848
John McCallb1cd7da2010-06-04 08:34:12 +0000849 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000850 assert(!DS.isFriendSpecified());
851
John McCallb1cd7da2010-06-04 08:34:12 +0000852 bool isFunc = false;
853 if (D.isFunctionDeclarator())
854 isFunc = true;
855 else if (D.getNumTypeObjects() == 0 &&
856 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000857 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000858 isFunc = TDType->isFunctionType();
859 }
860
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000861 // C++ 9.2p6: A member shall not be declared to have automatic storage
862 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000863 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
864 // data members and cannot be applied to names declared const or static,
865 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000866 switch (DS.getStorageClassSpec()) {
867 case DeclSpec::SCS_unspecified:
868 case DeclSpec::SCS_typedef:
869 case DeclSpec::SCS_static:
870 // FALL THROUGH.
871 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000872 case DeclSpec::SCS_mutable:
873 if (isFunc) {
874 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000875 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000876 else
Chris Lattner3b054132008-11-19 05:08:23 +0000877 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000878
Sebastian Redl8071edb2008-11-17 23:24:37 +0000879 // FIXME: It would be nicer if the keyword was ignored only for this
880 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000881 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000882 }
883 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000884 default:
885 if (DS.getStorageClassSpecLoc().isValid())
886 Diag(DS.getStorageClassSpecLoc(),
887 diag::err_storageclass_invalid_for_member);
888 else
889 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
890 D.getMutableDeclSpec().ClearStorageClassSpecs();
891 }
892
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000893 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
894 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000895 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000896
897 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000898 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000899 CXXScopeSpec &SS = D.getCXXScopeSpec();
900
901
902 if (SS.isSet() && !SS.isInvalid()) {
903 // The user provided a superfluous scope specifier inside a class
904 // definition:
905 //
906 // class X {
907 // int X::member;
908 // };
909 DeclContext *DC = 0;
910 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
911 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
912 << Name << FixItHint::CreateRemoval(SS.getRange());
913 else
914 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
915 << Name << SS.getRange();
916
917 SS.clear();
918 }
919
Douglas Gregor3447e762009-08-20 22:52:58 +0000920 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000921 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
922 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000923 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000924 } else {
John McCall48871652010-08-21 09:40:31 +0000925 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000926 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000927 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000928 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000929
930 // Non-instance-fields can't have a bitfield.
931 if (BitWidth) {
932 if (Member->isInvalidDecl()) {
933 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000934 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000935 // C++ 9.6p3: A bit-field shall not be a static member.
936 // "static member 'A' cannot be a bit-field"
937 Diag(Loc, diag::err_static_not_bitfield)
938 << Name << BitWidth->getSourceRange();
939 } else if (isa<TypedefDecl>(Member)) {
940 // "typedef member 'x' cannot be a bit-field"
941 Diag(Loc, diag::err_typedef_not_bitfield)
942 << Name << BitWidth->getSourceRange();
943 } else {
944 // A function typedef ("typedef int f(); f a;").
945 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
946 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000947 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000948 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattnerd26760a2009-03-05 23:01:03 +0000951 BitWidth = 0;
952 Member->setInvalidDecl();
953 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000954
955 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregor3447e762009-08-20 22:52:58 +0000957 // If we have declared a member function template, set the access of the
958 // templated declaration as well.
959 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
960 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000961 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000962
Douglas Gregor92751d42008-11-17 22:58:34 +0000963 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000964
Douglas Gregor0c880302009-03-11 23:00:04 +0000965 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000966 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000967 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000968 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000969
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000970 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000971 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +0000972 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000973 }
John McCall48871652010-08-21 09:40:31 +0000974 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000975}
976
Douglas Gregor15e77a22009-12-31 09:10:24 +0000977/// \brief Find the direct and/or virtual base specifiers that
978/// correspond to the given base type, for use in base initialization
979/// within a constructor.
980static bool FindBaseInitializer(Sema &SemaRef,
981 CXXRecordDecl *ClassDecl,
982 QualType BaseType,
983 const CXXBaseSpecifier *&DirectBaseSpec,
984 const CXXBaseSpecifier *&VirtualBaseSpec) {
985 // First, check for a direct base class.
986 DirectBaseSpec = 0;
987 for (CXXRecordDecl::base_class_const_iterator Base
988 = ClassDecl->bases_begin();
989 Base != ClassDecl->bases_end(); ++Base) {
990 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
991 // We found a direct base of this type. That's what we're
992 // initializing.
993 DirectBaseSpec = &*Base;
994 break;
995 }
996 }
997
998 // Check for a virtual base class.
999 // FIXME: We might be able to short-circuit this if we know in advance that
1000 // there are no virtual bases.
1001 VirtualBaseSpec = 0;
1002 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1003 // We haven't found a base yet; search the class hierarchy for a
1004 // virtual base class.
1005 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1006 /*DetectVirtual=*/false);
1007 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1008 BaseType, Paths)) {
1009 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1010 Path != Paths.end(); ++Path) {
1011 if (Path->back().Base->isVirtual()) {
1012 VirtualBaseSpec = Path->back().Base;
1013 break;
1014 }
1015 }
1016 }
1017 }
1018
1019 return DirectBaseSpec || VirtualBaseSpec;
1020}
1021
Douglas Gregore8381c02008-11-05 04:29:56 +00001022/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001023MemInitResult
John McCall48871652010-08-21 09:40:31 +00001024Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001025 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001026 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001027 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001028 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001029 SourceLocation IdLoc,
1030 SourceLocation LParenLoc,
1031 ExprTy **Args, unsigned NumArgs,
Douglas Gregore8381c02008-11-05 04:29:56 +00001032 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001033 if (!ConstructorD)
1034 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001036 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001037
1038 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001039 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001040 if (!Constructor) {
1041 // The user wrote a constructor initializer on a function that is
1042 // not a C++ constructor. Ignore the error for now, because we may
1043 // have more member initializers coming; we'll diagnose it just
1044 // once in ActOnMemInitializers.
1045 return true;
1046 }
1047
1048 CXXRecordDecl *ClassDecl = Constructor->getParent();
1049
1050 // C++ [class.base.init]p2:
1051 // Names in a mem-initializer-id are looked up in the scope of the
1052 // constructor’s class and, if not found in that scope, are looked
1053 // up in the scope containing the constructor’s
1054 // definition. [Note: if the constructor’s class contains a member
1055 // with the same name as a direct or virtual base class of the
1056 // class, a mem-initializer-id naming the member or base class and
1057 // composed of a single identifier refers to the class member. A
1058 // mem-initializer-id for the hidden base class may be specified
1059 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001060 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001061 // Look for a member, first.
1062 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001063 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001064 = ClassDecl->lookup(MemberOrBase);
1065 if (Result.first != Result.second)
1066 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001067
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001068 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001069
Eli Friedman8e1433b2009-07-29 19:44:27 +00001070 if (Member)
1071 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001072 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001073 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001074 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001075 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001076 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001077
1078 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001079 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001080 } else {
1081 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1082 LookupParsedName(R, S, &SS);
1083
1084 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1085 if (!TyD) {
1086 if (R.isAmbiguous()) return true;
1087
John McCallda6841b2010-04-09 19:01:14 +00001088 // We don't want access-control diagnostics here.
1089 R.suppressDiagnostics();
1090
Douglas Gregora3b624a2010-01-19 06:46:48 +00001091 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1092 bool NotUnknownSpecialization = false;
1093 DeclContext *DC = computeDeclContext(SS, false);
1094 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1095 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1096
1097 if (!NotUnknownSpecialization) {
1098 // When the scope specifier can refer to a member of an unknown
1099 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001100 BaseType = CheckTypenameType(ETK_None,
1101 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001102 *MemberOrBase, SourceLocation(),
1103 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001104 if (BaseType.isNull())
1105 return true;
1106
Douglas Gregora3b624a2010-01-19 06:46:48 +00001107 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001108 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001109 }
1110 }
1111
Douglas Gregor15e77a22009-12-31 09:10:24 +00001112 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001113 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001114 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1115 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001116 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001117 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001118 // We have found a non-static data member with a similar
1119 // name to what was typed; complain and initialize that
1120 // member.
1121 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1122 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001123 << FixItHint::CreateReplacement(R.getNameLoc(),
1124 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001125 Diag(Member->getLocation(), diag::note_previous_decl)
1126 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001127
1128 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1129 LParenLoc, RParenLoc);
1130 }
1131 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1132 const CXXBaseSpecifier *DirectBaseSpec;
1133 const CXXBaseSpecifier *VirtualBaseSpec;
1134 if (FindBaseInitializer(*this, ClassDecl,
1135 Context.getTypeDeclType(Type),
1136 DirectBaseSpec, VirtualBaseSpec)) {
1137 // We have found a direct or virtual base class with a
1138 // similar name to what was typed; complain and initialize
1139 // that base class.
1140 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1141 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001142 << FixItHint::CreateReplacement(R.getNameLoc(),
1143 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001144
1145 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1146 : VirtualBaseSpec;
1147 Diag(BaseSpec->getSourceRange().getBegin(),
1148 diag::note_base_class_specified_here)
1149 << BaseSpec->getType()
1150 << BaseSpec->getSourceRange();
1151
Douglas Gregor15e77a22009-12-31 09:10:24 +00001152 TyD = Type;
1153 }
1154 }
1155 }
1156
Douglas Gregora3b624a2010-01-19 06:46:48 +00001157 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001158 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1159 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1160 return true;
1161 }
John McCallb5a0d312009-12-21 10:41:20 +00001162 }
1163
Douglas Gregora3b624a2010-01-19 06:46:48 +00001164 if (BaseType.isNull()) {
1165 BaseType = Context.getTypeDeclType(TyD);
1166 if (SS.isSet()) {
1167 NestedNameSpecifier *Qualifier =
1168 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001169
Douglas Gregora3b624a2010-01-19 06:46:48 +00001170 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001171 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001172 }
John McCallb5a0d312009-12-21 10:41:20 +00001173 }
1174 }
Mike Stump11289f42009-09-09 15:08:12 +00001175
John McCallbcd03502009-12-07 02:54:59 +00001176 if (!TInfo)
1177 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001178
John McCallbcd03502009-12-07 02:54:59 +00001179 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001180 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001181}
1182
John McCalle22a04a2009-11-04 23:02:40 +00001183/// Checks an initializer expression for use of uninitialized fields, such as
1184/// containing the field that is being initialized. Returns true if there is an
1185/// uninitialized field was used an updates the SourceLocation parameter; false
1186/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001187static bool InitExprContainsUninitializedFields(const Stmt *S,
1188 const FieldDecl *LhsField,
1189 SourceLocation *L) {
1190 if (isa<CallExpr>(S)) {
1191 // Do not descend into function calls or constructors, as the use
1192 // of an uninitialized field may be valid. One would have to inspect
1193 // the contents of the function/ctor to determine if it is safe or not.
1194 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1195 // may be safe, depending on what the function/ctor does.
1196 return false;
1197 }
1198 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1199 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001200
1201 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1202 // The member expression points to a static data member.
1203 assert(VD->isStaticDataMember() &&
1204 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001205 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001206 return false;
1207 }
1208
1209 if (isa<EnumConstantDecl>(RhsField)) {
1210 // The member expression points to an enum.
1211 return false;
1212 }
1213
John McCalle22a04a2009-11-04 23:02:40 +00001214 if (RhsField == LhsField) {
1215 // Initializing a field with itself. Throw a warning.
1216 // But wait; there are exceptions!
1217 // Exception #1: The field may not belong to this record.
1218 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001219 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001220 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1221 // Even though the field matches, it does not belong to this record.
1222 return false;
1223 }
1224 // None of the exceptions triggered; return true to indicate an
1225 // uninitialized field was used.
1226 *L = ME->getMemberLoc();
1227 return true;
1228 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001229 } else if (isa<SizeOfAlignOfExpr>(S)) {
1230 // sizeof/alignof doesn't reference contents, do not warn.
1231 return false;
1232 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1233 // address-of doesn't reference contents (the pointer may be dereferenced
1234 // in the same expression but it would be rare; and weird).
1235 if (UOE->getOpcode() == UO_AddrOf)
1236 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001237 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001238 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1239 it != e; ++it) {
1240 if (!*it) {
1241 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001242 continue;
1243 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001244 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1245 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001246 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001247 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001248}
1249
John McCallfaf5fb42010-08-26 23:41:50 +00001250MemInitResult
Eli Friedman8e1433b2009-07-29 19:44:27 +00001251Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1252 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001253 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001254 SourceLocation RParenLoc) {
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001255 if (Member->isInvalidDecl())
1256 return true;
1257
John McCalle22a04a2009-11-04 23:02:40 +00001258 // Diagnose value-uses of fields to initialize themselves, e.g.
1259 // foo(foo)
1260 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001261 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001262 for (unsigned i = 0; i < NumArgs; ++i) {
1263 SourceLocation L;
1264 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1265 // FIXME: Return true in the case when other fields are used before being
1266 // uninitialized. For example, let this field be the i'th field. When
1267 // initializing the i'th field, throw a warning if any of the >= i'th
1268 // fields are used, as they are not yet initialized.
1269 // Right now we are only handling the case where the i'th field uses
1270 // itself in its initializer.
1271 Diag(L, diag::warn_field_is_uninit);
1272 }
1273 }
1274
Eli Friedman8e1433b2009-07-29 19:44:27 +00001275 bool HasDependentArg = false;
1276 for (unsigned i = 0; i < NumArgs; i++)
1277 HasDependentArg |= Args[i]->isTypeDependent();
1278
Eli Friedman9255adf2010-07-24 21:19:15 +00001279 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001280 // Can't check initialization for a member of dependent type or when
1281 // any of the arguments are type-dependent expressions.
John McCallb268a282010-08-23 23:25:46 +00001282 Expr *Init
1283 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1284 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001285
1286 // Erase any temporaries within this evaluation context; we're not
1287 // going to track them in the AST, since we'll be rebuilding the
1288 // ASTs during template instantiation.
1289 ExprTemporaries.erase(
1290 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1291 ExprTemporaries.end());
1292
1293 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1294 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001295 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001296 RParenLoc);
1297
Douglas Gregore8381c02008-11-05 04:29:56 +00001298 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001299
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001300 // Initialize the member.
1301 InitializedEntity MemberEntity =
1302 InitializedEntity::InitializeMember(Member, 0);
1303 InitializationKind Kind =
1304 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1305
1306 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1307
John McCalldadc5752010-08-24 06:29:42 +00001308 ExprResult MemberInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001309 InitSeq.Perform(*this, MemberEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001310 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001311 if (MemberInit.isInvalid())
1312 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001313
1314 CheckImplicitConversions(MemberInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001315
1316 // C++0x [class.base.init]p7:
1317 // The initialization of each base and member constitutes a
1318 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001319 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001320 if (MemberInit.isInvalid())
1321 return true;
1322
1323 // If we are in a dependent context, template instantiation will
1324 // perform this type-checking again. Just save the arguments that we
1325 // received in a ParenListExpr.
1326 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1327 // of the information that we have about the member
1328 // initializer. However, deconstructing the ASTs is a dicey process,
1329 // and this approach is far more likely to get the corner cases right.
1330 if (CurContext->isDependentContext()) {
John McCallb268a282010-08-23 23:25:46 +00001331 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1332 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001333 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1334 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001335 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001336 RParenLoc);
1337 }
1338
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001339 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001340 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001341 MemberInit.get(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001342 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001343}
1344
John McCallfaf5fb42010-08-26 23:41:50 +00001345MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001346Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001347 Expr **Args, unsigned NumArgs,
1348 SourceLocation LParenLoc, SourceLocation RParenLoc,
1349 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001350 bool HasDependentArg = false;
1351 for (unsigned i = 0; i < NumArgs; i++)
1352 HasDependentArg |= Args[i]->isTypeDependent();
1353
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001354 SourceLocation BaseLoc
1355 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1356
1357 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1358 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1359 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1360
1361 // C++ [class.base.init]p2:
1362 // [...] Unless the mem-initializer-id names a nonstatic data
1363 // member of the constructor’s class or a direct or virtual base
1364 // of that class, the mem-initializer is ill-formed. A
1365 // mem-initializer-list can initialize a base class using any
1366 // name that denotes that base class type.
1367 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1368
1369 // Check for direct and virtual base classes.
1370 const CXXBaseSpecifier *DirectBaseSpec = 0;
1371 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1372 if (!Dependent) {
1373 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1374 VirtualBaseSpec);
1375
1376 // C++ [base.class.init]p2:
1377 // Unless the mem-initializer-id names a nonstatic data member of the
1378 // constructor's class or a direct or virtual base of that class, the
1379 // mem-initializer is ill-formed.
1380 if (!DirectBaseSpec && !VirtualBaseSpec) {
1381 // If the class has any dependent bases, then it's possible that
1382 // one of those types will resolve to the same type as
1383 // BaseType. Therefore, just treat this as a dependent base
1384 // class initialization. FIXME: Should we try to check the
1385 // initialization anyway? It seems odd.
1386 if (ClassDecl->hasAnyDependentBases())
1387 Dependent = true;
1388 else
1389 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1390 << BaseType << Context.getTypeDeclType(ClassDecl)
1391 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1392 }
1393 }
1394
1395 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001396 // Can't check initialization for a base of dependent type or when
1397 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001398 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001399 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1400 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001401
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001402 // Erase any temporaries within this evaluation context; we're not
1403 // going to track them in the AST, since we'll be rebuilding the
1404 // ASTs during template instantiation.
1405 ExprTemporaries.erase(
1406 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1407 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001409 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001410 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001411 LParenLoc,
1412 BaseInit.takeAs<Expr>(),
1413 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001414 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415
1416 // C++ [base.class.init]p2:
1417 // If a mem-initializer-id is ambiguous because it designates both
1418 // a direct non-virtual base class and an inherited virtual base
1419 // class, the mem-initializer is ill-formed.
1420 if (DirectBaseSpec && VirtualBaseSpec)
1421 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001422 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001423
1424 CXXBaseSpecifier *BaseSpec
1425 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1426 if (!BaseSpec)
1427 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1428
1429 // Initialize the base.
1430 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001431 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001432 InitializationKind Kind =
1433 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1434
1435 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1436
John McCalldadc5752010-08-24 06:29:42 +00001437 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001438 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001439 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001440 if (BaseInit.isInvalid())
1441 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001442
1443 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001444
1445 // C++0x [class.base.init]p7:
1446 // The initialization of each base and member constitutes a
1447 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001448 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001449 if (BaseInit.isInvalid())
1450 return true;
1451
1452 // If we are in a dependent context, template instantiation will
1453 // perform this type-checking again. Just save the arguments that we
1454 // received in a ParenListExpr.
1455 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1456 // of the information that we have about the base
1457 // initializer. However, deconstructing the ASTs is a dicey process,
1458 // and this approach is far more likely to get the corner cases right.
1459 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001460 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001461 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1462 RParenLoc));
1463 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001464 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001465 LParenLoc,
1466 Init.takeAs<Expr>(),
1467 RParenLoc);
1468 }
1469
1470 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001471 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001472 LParenLoc,
1473 BaseInit.takeAs<Expr>(),
1474 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001475}
1476
Anders Carlsson1b00e242010-04-23 03:10:23 +00001477/// ImplicitInitializerKind - How an implicit base or member initializer should
1478/// initialize its base or member.
1479enum ImplicitInitializerKind {
1480 IIK_Default,
1481 IIK_Copy,
1482 IIK_Move
1483};
1484
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001485static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001486BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001487 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001488 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001489 bool IsInheritedVirtualBase,
1490 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001491 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001492 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1493 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001494
John McCalldadc5752010-08-24 06:29:42 +00001495 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001496
1497 switch (ImplicitInitKind) {
1498 case IIK_Default: {
1499 InitializationKind InitKind
1500 = InitializationKind::CreateDefault(Constructor->getLocation());
1501 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1502 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001503 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001504 break;
1505 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001506
Anders Carlsson1b00e242010-04-23 03:10:23 +00001507 case IIK_Copy: {
1508 ParmVarDecl *Param = Constructor->getParamDecl(0);
1509 QualType ParamType = Param->getType().getNonReferenceType();
1510
1511 Expr *CopyCtorArg =
1512 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001513 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001514
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001515 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001516 QualType ArgTy =
1517 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1518 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001519
1520 CXXCastPath BasePath;
1521 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001522 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001523 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001524 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001525
Anders Carlsson1b00e242010-04-23 03:10:23 +00001526 InitializationKind InitKind
1527 = InitializationKind::CreateDirect(Constructor->getLocation(),
1528 SourceLocation(), SourceLocation());
1529 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1530 &CopyCtorArg, 1);
1531 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001532 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001533 break;
1534 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001535
Anders Carlsson1b00e242010-04-23 03:10:23 +00001536 case IIK_Move:
1537 assert(false && "Unhandled initializer kind!");
1538 }
John McCallb268a282010-08-23 23:25:46 +00001539
1540 if (BaseInit.isInvalid())
1541 return true;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001542
John McCallb268a282010-08-23 23:25:46 +00001543 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001544 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001545 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001546
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001547 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001548 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1549 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1550 SourceLocation()),
1551 BaseSpec->isVirtual(),
1552 SourceLocation(),
1553 BaseInit.takeAs<Expr>(),
1554 SourceLocation());
1555
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001556 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001557}
1558
Anders Carlsson3c1db572010-04-23 02:15:47 +00001559static bool
1560BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001561 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001562 FieldDecl *Field,
1563 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001564 if (Field->isInvalidDecl())
1565 return true;
1566
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001567 SourceLocation Loc = Constructor->getLocation();
1568
Anders Carlsson423f5d82010-04-23 16:04:08 +00001569 if (ImplicitInitKind == IIK_Copy) {
1570 ParmVarDecl *Param = Constructor->getParamDecl(0);
1571 QualType ParamType = Param->getType().getNonReferenceType();
1572
1573 Expr *MemberExprBase =
1574 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001575 Loc, ParamType, 0);
1576
1577 // Build a reference to this field within the parameter.
1578 CXXScopeSpec SS;
1579 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1580 Sema::LookupMemberName);
1581 MemberLookup.addDecl(Field, AS_public);
1582 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001583 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001584 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001585 ParamType, Loc,
1586 /*IsArrow=*/false,
1587 SS,
1588 /*FirstQualifierInScope=*/0,
1589 MemberLookup,
1590 /*TemplateArgs=*/0);
1591 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001592 return true;
1593
Douglas Gregor94f9a482010-05-05 05:51:00 +00001594 // When the field we are copying is an array, create index variables for
1595 // each dimension of the array. We use these index variables to subscript
1596 // the source array, and other clients (e.g., CodeGen) will perform the
1597 // necessary iteration with these index variables.
1598 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1599 QualType BaseType = Field->getType();
1600 QualType SizeType = SemaRef.Context.getSizeType();
1601 while (const ConstantArrayType *Array
1602 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1603 // Create the iteration variable for this array index.
1604 IdentifierInfo *IterationVarName = 0;
1605 {
1606 llvm::SmallString<8> Str;
1607 llvm::raw_svector_ostream OS(Str);
1608 OS << "__i" << IndexVariables.size();
1609 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1610 }
1611 VarDecl *IterationVar
1612 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1613 IterationVarName, SizeType,
1614 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001615 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001616 IndexVariables.push_back(IterationVar);
1617
1618 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001619 ExprResult IterationVarRef
Douglas Gregor94f9a482010-05-05 05:51:00 +00001620 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1621 assert(!IterationVarRef.isInvalid() &&
1622 "Reference to invented variable cannot fail!");
1623
1624 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001625 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001626 Loc,
John McCallb268a282010-08-23 23:25:46 +00001627 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001628 Loc);
1629 if (CopyCtorArg.isInvalid())
1630 return true;
1631
1632 BaseType = Array->getElementType();
1633 }
1634
1635 // Construct the entity that we will be initializing. For an array, this
1636 // will be first element in the array, which may require several levels
1637 // of array-subscript entities.
1638 llvm::SmallVector<InitializedEntity, 4> Entities;
1639 Entities.reserve(1 + IndexVariables.size());
1640 Entities.push_back(InitializedEntity::InitializeMember(Field));
1641 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1642 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1643 0,
1644 Entities.back()));
1645
1646 // Direct-initialize to use the copy constructor.
1647 InitializationKind InitKind =
1648 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1649
1650 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1651 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1652 &CopyCtorArgE, 1);
1653
John McCalldadc5752010-08-24 06:29:42 +00001654 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001655 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001656 MultiExprArg(&CopyCtorArgE, 1));
John McCallb268a282010-08-23 23:25:46 +00001657 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor94f9a482010-05-05 05:51:00 +00001658 if (MemberInit.isInvalid())
1659 return true;
1660
1661 CXXMemberInit
1662 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1663 MemberInit.takeAs<Expr>(), Loc,
1664 IndexVariables.data(),
1665 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001666 return false;
1667 }
1668
Anders Carlsson423f5d82010-04-23 16:04:08 +00001669 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1670
Anders Carlsson3c1db572010-04-23 02:15:47 +00001671 QualType FieldBaseElementType =
1672 SemaRef.Context.getBaseElementType(Field->getType());
1673
Anders Carlsson3c1db572010-04-23 02:15:47 +00001674 if (FieldBaseElementType->isRecordType()) {
1675 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001676 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001677 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001678
1679 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001680 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001681 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001682 if (MemberInit.isInvalid())
1683 return true;
1684
1685 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001686 if (MemberInit.isInvalid())
1687 return true;
1688
1689 CXXMemberInit =
1690 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001691 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001692 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001693 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001694 return false;
1695 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001696
1697 if (FieldBaseElementType->isReferenceType()) {
1698 SemaRef.Diag(Constructor->getLocation(),
1699 diag::err_uninitialized_member_in_ctor)
1700 << (int)Constructor->isImplicit()
1701 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1702 << 0 << Field->getDeclName();
1703 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1704 return true;
1705 }
1706
1707 if (FieldBaseElementType.isConstQualified()) {
1708 SemaRef.Diag(Constructor->getLocation(),
1709 diag::err_uninitialized_member_in_ctor)
1710 << (int)Constructor->isImplicit()
1711 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1712 << 1 << Field->getDeclName();
1713 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1714 return true;
1715 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001716
1717 // Nothing to initialize.
1718 CXXMemberInit = 0;
1719 return false;
1720}
John McCallbc83b3f2010-05-20 23:23:51 +00001721
1722namespace {
1723struct BaseAndFieldInfo {
1724 Sema &S;
1725 CXXConstructorDecl *Ctor;
1726 bool AnyErrorsInInits;
1727 ImplicitInitializerKind IIK;
1728 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1729 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1730
1731 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1732 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1733 // FIXME: Handle implicit move constructors.
1734 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1735 IIK = IIK_Copy;
1736 else
1737 IIK = IIK_Default;
1738 }
1739};
1740}
1741
Chandler Carruth139e9622010-06-30 02:59:29 +00001742static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1743 FieldDecl *Top, FieldDecl *Field,
1744 CXXBaseOrMemberInitializer *Init) {
1745 // If the member doesn't need to be initialized, Init will still be null.
1746 if (!Init)
1747 return;
1748
1749 Info.AllToInit.push_back(Init);
1750 if (Field != Top) {
1751 Init->setMember(Top);
1752 Init->setAnonUnionMember(Field);
1753 }
1754}
1755
John McCallbc83b3f2010-05-20 23:23:51 +00001756static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1757 FieldDecl *Top, FieldDecl *Field) {
1758
Chandler Carruth139e9622010-06-30 02:59:29 +00001759 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001760 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001761 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001762 return false;
1763 }
1764
1765 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1766 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1767 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001768 CXXRecordDecl *FieldClassDecl
1769 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001770
1771 // Even though union members never have non-trivial default
1772 // constructions in C++03, we still build member initializers for aggregate
1773 // record types which can be union members, and C++0x allows non-trivial
1774 // default constructors for union members, so we ensure that only one
1775 // member is initialized for these.
1776 if (FieldClassDecl->isUnion()) {
1777 // First check for an explicit initializer for one field.
1778 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1779 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1780 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1781 RecordFieldInitializer(Info, Top, *FA, Init);
1782
1783 // Once we've initialized a field of an anonymous union, the union
1784 // field in the class is also initialized, so exit immediately.
1785 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001786 } else if ((*FA)->isAnonymousStructOrUnion()) {
1787 if (CollectFieldInitializer(Info, Top, *FA))
1788 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001789 }
1790 }
1791
1792 // Fallthrough and construct a default initializer for the union as
1793 // a whole, which can call its default constructor if such a thing exists
1794 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1795 // behavior going forward with C++0x, when anonymous unions there are
1796 // finalized, we should revisit this.
1797 } else {
1798 // For structs, we simply descend through to initialize all members where
1799 // necessary.
1800 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1801 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1802 if (CollectFieldInitializer(Info, Top, *FA))
1803 return true;
1804 }
1805 }
John McCallbc83b3f2010-05-20 23:23:51 +00001806 }
1807
1808 // Don't try to build an implicit initializer if there were semantic
1809 // errors in any of the initializers (and therefore we might be
1810 // missing some that the user actually wrote).
1811 if (Info.AnyErrorsInInits)
1812 return false;
1813
1814 CXXBaseOrMemberInitializer *Init = 0;
1815 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1816 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001817
Chandler Carruth139e9622010-06-30 02:59:29 +00001818 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001819 return false;
1820}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001821
Eli Friedman9cf6b592009-11-09 19:20:36 +00001822bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001823Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001824 CXXBaseOrMemberInitializer **Initializers,
1825 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001826 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001827 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001828 // Just store the initializers as written, they will be checked during
1829 // instantiation.
1830 if (NumInitializers > 0) {
1831 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1832 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1833 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1834 memcpy(baseOrMemberInitializers, Initializers,
1835 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1836 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1837 }
1838
1839 return false;
1840 }
1841
John McCallbc83b3f2010-05-20 23:23:51 +00001842 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001843
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001844 // We need to build the initializer AST according to order of construction
1845 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001846 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001847 if (!ClassDecl)
1848 return true;
1849
Eli Friedman9cf6b592009-11-09 19:20:36 +00001850 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001851
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001852 for (unsigned i = 0; i < NumInitializers; i++) {
1853 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001854
1855 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001856 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001857 else
John McCallbc83b3f2010-05-20 23:23:51 +00001858 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001859 }
1860
Anders Carlsson43c64af2010-04-21 19:52:01 +00001861 // Keep track of the direct virtual bases.
1862 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1863 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1864 E = ClassDecl->bases_end(); I != E; ++I) {
1865 if (I->isVirtual())
1866 DirectVBases.insert(I);
1867 }
1868
Anders Carlssondb0a9652010-04-02 06:26:44 +00001869 // Push virtual bases before others.
1870 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1871 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1872
1873 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001874 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1875 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001876 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001877 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001878 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001879 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001880 VBase, IsInheritedVirtualBase,
1881 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001882 HadError = true;
1883 continue;
1884 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001885
John McCallbc83b3f2010-05-20 23:23:51 +00001886 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001887 }
1888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
John McCallbc83b3f2010-05-20 23:23:51 +00001890 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001891 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1892 E = ClassDecl->bases_end(); Base != E; ++Base) {
1893 // Virtuals are in the virtual base list and already constructed.
1894 if (Base->isVirtual())
1895 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001896
Anders Carlssondb0a9652010-04-02 06:26:44 +00001897 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001898 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1899 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001900 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001901 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001902 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001903 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001904 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001905 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001906 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001907 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001908
John McCallbc83b3f2010-05-20 23:23:51 +00001909 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001910 }
1911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
John McCallbc83b3f2010-05-20 23:23:51 +00001913 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001914 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001915 E = ClassDecl->field_end(); Field != E; ++Field) {
1916 if ((*Field)->getType()->isIncompleteArrayType()) {
1917 assert(ClassDecl->hasFlexibleArrayMember() &&
1918 "Incomplete array type is not valid");
1919 continue;
1920 }
John McCallbc83b3f2010-05-20 23:23:51 +00001921 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001922 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001923 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
John McCallbc83b3f2010-05-20 23:23:51 +00001925 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001926 if (NumInitializers > 0) {
1927 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1928 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1929 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001930 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001931 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001932 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001933
John McCalla6309952010-03-16 21:39:52 +00001934 // Constructors implicitly reference the base and member
1935 // destructors.
1936 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1937 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001938 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001939
1940 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001941}
1942
Eli Friedman952c15d2009-07-21 19:28:10 +00001943static void *GetKeyForTopLevelField(FieldDecl *Field) {
1944 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001945 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001946 if (RT->getDecl()->isAnonymousStructOrUnion())
1947 return static_cast<void *>(RT->getDecl());
1948 }
1949 return static_cast<void *>(Field);
1950}
1951
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001952static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1953 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001954}
1955
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001956static void *GetKeyForMember(ASTContext &Context,
1957 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001958 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001959 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001960 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001961
Eli Friedman952c15d2009-07-21 19:28:10 +00001962 // For fields injected into the class via declaration of an anonymous union,
1963 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001964 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001965
Anders Carlssona942dcd2010-03-30 15:39:27 +00001966 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1967 // data member of the class. Data member used in the initializer list is
1968 // in AnonUnionMember field.
1969 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1970 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001971
John McCall23eebd92010-04-10 09:28:51 +00001972 // If the field is a member of an anonymous struct or union, our key
1973 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001974 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001975 if (RD->isAnonymousStructOrUnion()) {
1976 while (true) {
1977 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1978 if (Parent->isAnonymousStructOrUnion())
1979 RD = Parent;
1980 else
1981 break;
1982 }
1983
Anders Carlsson83ac3122010-03-30 16:19:37 +00001984 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Anders Carlssona942dcd2010-03-30 15:39:27 +00001987 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001988}
1989
Anders Carlssone857b292010-04-02 03:37:03 +00001990static void
1991DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001992 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001993 CXXBaseOrMemberInitializer **Inits,
1994 unsigned NumInits) {
1995 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001996 return;
Mike Stump11289f42009-09-09 15:08:12 +00001997
John McCallbb7b6582010-04-10 07:37:23 +00001998 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1999 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002000 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002001
John McCallbb7b6582010-04-10 07:37:23 +00002002 // Build the list of bases and members in the order that they'll
2003 // actually be initialized. The explicit initializers should be in
2004 // this same order but may be missing things.
2005 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002007 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2008
John McCallbb7b6582010-04-10 07:37:23 +00002009 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002010 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002011 ClassDecl->vbases_begin(),
2012 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002013 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002014
John McCallbb7b6582010-04-10 07:37:23 +00002015 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002016 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002017 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002018 if (Base->isVirtual())
2019 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002020 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
John McCallbb7b6582010-04-10 07:37:23 +00002023 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002024 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2025 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002026 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002027
John McCallbb7b6582010-04-10 07:37:23 +00002028 unsigned NumIdealInits = IdealInitKeys.size();
2029 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002030
John McCallbb7b6582010-04-10 07:37:23 +00002031 CXXBaseOrMemberInitializer *PrevInit = 0;
2032 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2033 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2034 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2035
2036 // Scan forward to try to find this initializer in the idealized
2037 // initializers list.
2038 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2039 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002040 break;
John McCallbb7b6582010-04-10 07:37:23 +00002041
2042 // If we didn't find this initializer, it must be because we
2043 // scanned past it on a previous iteration. That can only
2044 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002045 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002046 Sema::SemaDiagnosticBuilder D =
2047 SemaRef.Diag(PrevInit->getSourceLocation(),
2048 diag::warn_initializer_out_of_order);
2049
2050 if (PrevInit->isMemberInitializer())
2051 D << 0 << PrevInit->getMember()->getDeclName();
2052 else
2053 D << 1 << PrevInit->getBaseClassInfo()->getType();
2054
2055 if (Init->isMemberInitializer())
2056 D << 0 << Init->getMember()->getDeclName();
2057 else
2058 D << 1 << Init->getBaseClassInfo()->getType();
2059
2060 // Move back to the initializer's location in the ideal list.
2061 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2062 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002063 break;
John McCallbb7b6582010-04-10 07:37:23 +00002064
2065 assert(IdealIndex != NumIdealInits &&
2066 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002067 }
John McCallbb7b6582010-04-10 07:37:23 +00002068
2069 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002070 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002071}
2072
John McCall23eebd92010-04-10 09:28:51 +00002073namespace {
2074bool CheckRedundantInit(Sema &S,
2075 CXXBaseOrMemberInitializer *Init,
2076 CXXBaseOrMemberInitializer *&PrevInit) {
2077 if (!PrevInit) {
2078 PrevInit = Init;
2079 return false;
2080 }
2081
2082 if (FieldDecl *Field = Init->getMember())
2083 S.Diag(Init->getSourceLocation(),
2084 diag::err_multiple_mem_initialization)
2085 << Field->getDeclName()
2086 << Init->getSourceRange();
2087 else {
2088 Type *BaseClass = Init->getBaseClass();
2089 assert(BaseClass && "neither field nor base");
2090 S.Diag(Init->getSourceLocation(),
2091 diag::err_multiple_base_initialization)
2092 << QualType(BaseClass, 0)
2093 << Init->getSourceRange();
2094 }
2095 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2096 << 0 << PrevInit->getSourceRange();
2097
2098 return true;
2099}
2100
2101typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2102typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2103
2104bool CheckRedundantUnionInit(Sema &S,
2105 CXXBaseOrMemberInitializer *Init,
2106 RedundantUnionMap &Unions) {
2107 FieldDecl *Field = Init->getMember();
2108 RecordDecl *Parent = Field->getParent();
2109 if (!Parent->isAnonymousStructOrUnion())
2110 return false;
2111
2112 NamedDecl *Child = Field;
2113 do {
2114 if (Parent->isUnion()) {
2115 UnionEntry &En = Unions[Parent];
2116 if (En.first && En.first != Child) {
2117 S.Diag(Init->getSourceLocation(),
2118 diag::err_multiple_mem_union_initialization)
2119 << Field->getDeclName()
2120 << Init->getSourceRange();
2121 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2122 << 0 << En.second->getSourceRange();
2123 return true;
2124 } else if (!En.first) {
2125 En.first = Child;
2126 En.second = Init;
2127 }
2128 }
2129
2130 Child = Parent;
2131 Parent = cast<RecordDecl>(Parent->getDeclContext());
2132 } while (Parent->isAnonymousStructOrUnion());
2133
2134 return false;
2135}
2136}
2137
Anders Carlssone857b292010-04-02 03:37:03 +00002138/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002139void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002140 SourceLocation ColonLoc,
2141 MemInitTy **meminits, unsigned NumMemInits,
2142 bool AnyErrors) {
2143 if (!ConstructorDecl)
2144 return;
2145
2146 AdjustDeclIfTemplate(ConstructorDecl);
2147
2148 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002149 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002150
2151 if (!Constructor) {
2152 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2153 return;
2154 }
2155
2156 CXXBaseOrMemberInitializer **MemInits =
2157 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002158
2159 // Mapping for the duplicate initializers check.
2160 // For member initializers, this is keyed with a FieldDecl*.
2161 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002162 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002163
2164 // Mapping for the inconsistent anonymous-union initializers check.
2165 RedundantUnionMap MemberUnions;
2166
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002167 bool HadError = false;
2168 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002169 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002170
Abramo Bagnara341d7832010-05-26 18:09:23 +00002171 // Set the source order index.
2172 Init->setSourceOrder(i);
2173
John McCall23eebd92010-04-10 09:28:51 +00002174 if (Init->isMemberInitializer()) {
2175 FieldDecl *Field = Init->getMember();
2176 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2177 CheckRedundantUnionInit(*this, Init, MemberUnions))
2178 HadError = true;
2179 } else {
2180 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2181 if (CheckRedundantInit(*this, Init, Members[Key]))
2182 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002183 }
Anders Carlssone857b292010-04-02 03:37:03 +00002184 }
2185
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002186 if (HadError)
2187 return;
2188
Anders Carlssone857b292010-04-02 03:37:03 +00002189 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002190
2191 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002192}
2193
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002194void
John McCalla6309952010-03-16 21:39:52 +00002195Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2196 CXXRecordDecl *ClassDecl) {
2197 // Ignore dependent contexts.
2198 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002199 return;
John McCall1064d7e2010-03-16 05:22:47 +00002200
2201 // FIXME: all the access-control diagnostics are positioned on the
2202 // field/base declaration. That's probably good; that said, the
2203 // user might reasonably want to know why the destructor is being
2204 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002205
Anders Carlssondee9a302009-11-17 04:44:12 +00002206 // Non-static data members.
2207 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2208 E = ClassDecl->field_end(); I != E; ++I) {
2209 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002210 if (Field->isInvalidDecl())
2211 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002212 QualType FieldType = Context.getBaseElementType(Field->getType());
2213
2214 const RecordType* RT = FieldType->getAs<RecordType>();
2215 if (!RT)
2216 continue;
2217
2218 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2219 if (FieldClassDecl->hasTrivialDestructor())
2220 continue;
2221
Douglas Gregore71edda2010-07-01 22:47:18 +00002222 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002223 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002224 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002225 << Field->getDeclName()
2226 << FieldType);
2227
John McCalla6309952010-03-16 21:39:52 +00002228 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002229 }
2230
John McCall1064d7e2010-03-16 05:22:47 +00002231 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2232
Anders Carlssondee9a302009-11-17 04:44:12 +00002233 // Bases.
2234 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2235 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002236 // Bases are always records in a well-formed non-dependent class.
2237 const RecordType *RT = Base->getType()->getAs<RecordType>();
2238
2239 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002240 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002241 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002242
2243 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002244 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002245 if (BaseClassDecl->hasTrivialDestructor())
2246 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002247
Douglas Gregore71edda2010-07-01 22:47:18 +00002248 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002249
2250 // FIXME: caret should be on the start of the class name
2251 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002252 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002253 << Base->getType()
2254 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002255
John McCalla6309952010-03-16 21:39:52 +00002256 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002257 }
2258
2259 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002260 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2261 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002262
2263 // Bases are always records in a well-formed non-dependent class.
2264 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2265
2266 // Ignore direct virtual bases.
2267 if (DirectVirtualBases.count(RT))
2268 continue;
2269
Anders Carlssondee9a302009-11-17 04:44:12 +00002270 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002271 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002272 if (BaseClassDecl->hasTrivialDestructor())
2273 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002274
Douglas Gregore71edda2010-07-01 22:47:18 +00002275 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002276 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002277 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002278 << VBase->getType());
2279
John McCalla6309952010-03-16 21:39:52 +00002280 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002281 }
2282}
2283
John McCall48871652010-08-21 09:40:31 +00002284void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002285 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002286 return;
Mike Stump11289f42009-09-09 15:08:12 +00002287
Mike Stump11289f42009-09-09 15:08:12 +00002288 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002289 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002290 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002291}
2292
Mike Stump11289f42009-09-09 15:08:12 +00002293bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002294 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002295 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002296 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002297 else
John McCall02db245d2010-08-18 09:41:07 +00002298 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002299}
2300
Anders Carlssoneabf7702009-08-27 00:13:57 +00002301bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002302 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002303 if (!getLangOptions().CPlusPlus)
2304 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002305
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002306 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002307 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002308
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002309 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002310 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002311 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002312 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002313
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002314 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002315 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002316 }
Mike Stump11289f42009-09-09 15:08:12 +00002317
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002318 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002319 if (!RT)
2320 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002321
John McCall67da35c2010-02-04 22:26:26 +00002322 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002323
John McCall02db245d2010-08-18 09:41:07 +00002324 // We can't answer whether something is abstract until it has a
2325 // definition. If it's currently being defined, we'll walk back
2326 // over all the declarations when we have a full definition.
2327 const CXXRecordDecl *Def = RD->getDefinition();
2328 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002329 return false;
2330
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002331 if (!RD->isAbstract())
2332 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002333
Anders Carlssoneabf7702009-08-27 00:13:57 +00002334 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002335 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002336
John McCall02db245d2010-08-18 09:41:07 +00002337 return true;
2338}
2339
2340void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2341 // Check if we've already emitted the list of pure virtual functions
2342 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002343 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002344 return;
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregor4165bd62010-03-23 23:47:56 +00002346 CXXFinalOverriderMap FinalOverriders;
2347 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002348
Anders Carlssona2f74f32010-06-03 01:00:02 +00002349 // Keep a set of seen pure methods so we won't diagnose the same method
2350 // more than once.
2351 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2352
Douglas Gregor4165bd62010-03-23 23:47:56 +00002353 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2354 MEnd = FinalOverriders.end();
2355 M != MEnd;
2356 ++M) {
2357 for (OverridingMethods::iterator SO = M->second.begin(),
2358 SOEnd = M->second.end();
2359 SO != SOEnd; ++SO) {
2360 // C++ [class.abstract]p4:
2361 // A class is abstract if it contains or inherits at least one
2362 // pure virtual function for which the final overrider is pure
2363 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002364
Douglas Gregor4165bd62010-03-23 23:47:56 +00002365 //
2366 if (SO->second.size() != 1)
2367 continue;
2368
2369 if (!SO->second.front().Method->isPure())
2370 continue;
2371
Anders Carlssona2f74f32010-06-03 01:00:02 +00002372 if (!SeenPureMethods.insert(SO->second.front().Method))
2373 continue;
2374
Douglas Gregor4165bd62010-03-23 23:47:56 +00002375 Diag(SO->second.front().Method->getLocation(),
2376 diag::note_pure_virtual_function)
2377 << SO->second.front().Method->getDeclName();
2378 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002379 }
2380
2381 if (!PureVirtualClassDiagSet)
2382 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2383 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002384}
2385
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002386namespace {
John McCall02db245d2010-08-18 09:41:07 +00002387struct AbstractUsageInfo {
2388 Sema &S;
2389 CXXRecordDecl *Record;
2390 CanQualType AbstractType;
2391 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002392
John McCall02db245d2010-08-18 09:41:07 +00002393 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2394 : S(S), Record(Record),
2395 AbstractType(S.Context.getCanonicalType(
2396 S.Context.getTypeDeclType(Record))),
2397 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002398
John McCall02db245d2010-08-18 09:41:07 +00002399 void DiagnoseAbstractType() {
2400 if (Invalid) return;
2401 S.DiagnoseAbstractType(Record);
2402 Invalid = true;
2403 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002404
John McCall02db245d2010-08-18 09:41:07 +00002405 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2406};
2407
2408struct CheckAbstractUsage {
2409 AbstractUsageInfo &Info;
2410 const NamedDecl *Ctx;
2411
2412 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2413 : Info(Info), Ctx(Ctx) {}
2414
2415 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2416 switch (TL.getTypeLocClass()) {
2417#define ABSTRACT_TYPELOC(CLASS, PARENT)
2418#define TYPELOC(CLASS, PARENT) \
2419 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2420#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002421 }
John McCall02db245d2010-08-18 09:41:07 +00002422 }
Mike Stump11289f42009-09-09 15:08:12 +00002423
John McCall02db245d2010-08-18 09:41:07 +00002424 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2425 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2426 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2427 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2428 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002429 }
John McCall02db245d2010-08-18 09:41:07 +00002430 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002431
John McCall02db245d2010-08-18 09:41:07 +00002432 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2433 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2434 }
Mike Stump11289f42009-09-09 15:08:12 +00002435
John McCall02db245d2010-08-18 09:41:07 +00002436 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2437 // Visit the type parameters from a permissive context.
2438 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2439 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2440 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2441 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2442 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2443 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002444 }
John McCall02db245d2010-08-18 09:41:07 +00002445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
John McCall02db245d2010-08-18 09:41:07 +00002447 // Visit pointee types from a permissive context.
2448#define CheckPolymorphic(Type) \
2449 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2450 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2451 }
2452 CheckPolymorphic(PointerTypeLoc)
2453 CheckPolymorphic(ReferenceTypeLoc)
2454 CheckPolymorphic(MemberPointerTypeLoc)
2455 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002456
John McCall02db245d2010-08-18 09:41:07 +00002457 /// Handle all the types we haven't given a more specific
2458 /// implementation for above.
2459 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2460 // Every other kind of type that we haven't called out already
2461 // that has an inner type is either (1) sugar or (2) contains that
2462 // inner type in some way as a subobject.
2463 if (TypeLoc Next = TL.getNextTypeLoc())
2464 return Visit(Next, Sel);
2465
2466 // If there's no inner type and we're in a permissive context,
2467 // don't diagnose.
2468 if (Sel == Sema::AbstractNone) return;
2469
2470 // Check whether the type matches the abstract type.
2471 QualType T = TL.getType();
2472 if (T->isArrayType()) {
2473 Sel = Sema::AbstractArrayType;
2474 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002475 }
John McCall02db245d2010-08-18 09:41:07 +00002476 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2477 if (CT != Info.AbstractType) return;
2478
2479 // It matched; do some magic.
2480 if (Sel == Sema::AbstractArrayType) {
2481 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2482 << T << TL.getSourceRange();
2483 } else {
2484 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2485 << Sel << T << TL.getSourceRange();
2486 }
2487 Info.DiagnoseAbstractType();
2488 }
2489};
2490
2491void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2492 Sema::AbstractDiagSelID Sel) {
2493 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2494}
2495
2496}
2497
2498/// Check for invalid uses of an abstract type in a method declaration.
2499static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2500 CXXMethodDecl *MD) {
2501 // No need to do the check on definitions, which require that
2502 // the return/param types be complete.
2503 if (MD->isThisDeclarationADefinition())
2504 return;
2505
2506 // For safety's sake, just ignore it if we don't have type source
2507 // information. This should never happen for non-implicit methods,
2508 // but...
2509 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2510 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2511}
2512
2513/// Check for invalid uses of an abstract type within a class definition.
2514static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2515 CXXRecordDecl *RD) {
2516 for (CXXRecordDecl::decl_iterator
2517 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2518 Decl *D = *I;
2519 if (D->isImplicit()) continue;
2520
2521 // Methods and method templates.
2522 if (isa<CXXMethodDecl>(D)) {
2523 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2524 } else if (isa<FunctionTemplateDecl>(D)) {
2525 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2526 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2527
2528 // Fields and static variables.
2529 } else if (isa<FieldDecl>(D)) {
2530 FieldDecl *FD = cast<FieldDecl>(D);
2531 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2532 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2533 } else if (isa<VarDecl>(D)) {
2534 VarDecl *VD = cast<VarDecl>(D);
2535 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2536 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2537
2538 // Nested classes and class templates.
2539 } else if (isa<CXXRecordDecl>(D)) {
2540 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2541 } else if (isa<ClassTemplateDecl>(D)) {
2542 CheckAbstractClassUsage(Info,
2543 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2544 }
2545 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002546}
2547
Douglas Gregorc99f1552009-12-03 18:33:45 +00002548/// \brief Perform semantic checks on a class definition that has been
2549/// completing, introducing implicitly-declared members, checking for
2550/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002551void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002552 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002553 return;
2554
John McCall02db245d2010-08-18 09:41:07 +00002555 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2556 AbstractUsageInfo Info(*this, Record);
2557 CheckAbstractClassUsage(Info, Record);
2558 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002559
2560 // If this is not an aggregate type and has no user-declared constructor,
2561 // complain about any non-static data members of reference or const scalar
2562 // type, since they will never get initializers.
2563 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2564 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2565 bool Complained = false;
2566 for (RecordDecl::field_iterator F = Record->field_begin(),
2567 FEnd = Record->field_end();
2568 F != FEnd; ++F) {
2569 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002570 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002571 if (!Complained) {
2572 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2573 << Record->getTagKind() << Record;
2574 Complained = true;
2575 }
2576
2577 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2578 << F->getType()->isReferenceType()
2579 << F->getDeclName();
2580 }
2581 }
2582 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002583
2584 if (Record->isDynamicClass())
2585 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002586
2587 if (Record->getIdentifier()) {
2588 // C++ [class.mem]p13:
2589 // If T is the name of a class, then each of the following shall have a
2590 // name different from T:
2591 // - every member of every anonymous union that is a member of class T.
2592 //
2593 // C++ [class.mem]p14:
2594 // In addition, if class T has a user-declared constructor (12.1), every
2595 // non-static data member of class T shall have a name different from T.
2596 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
2597 R.first != R.second; ++R.first)
2598 if (FieldDecl *Field = dyn_cast<FieldDecl>(*R.first)) {
2599 if (Record->hasUserDeclaredConstructor() ||
2600 !Field->getDeclContext()->Equals(Record)) {
2601 Diag(Field->getLocation(), diag::err_member_name_of_class)
2602 << Field->getDeclName();
2603 break;
2604 }
2605 }
2606 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002607}
2608
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002609void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002610 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002611 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002612 SourceLocation RBrac,
2613 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002614 if (!TagDecl)
2615 return;
Mike Stump11289f42009-09-09 15:08:12 +00002616
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002617 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002618
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002619 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002620 // strict aliasing violation!
2621 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002622 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002623
Douglas Gregor0be31a22010-07-02 17:43:08 +00002624 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002625 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002626}
2627
Douglas Gregor95755162010-07-01 05:10:53 +00002628namespace {
2629 /// \brief Helper class that collects exception specifications for
2630 /// implicitly-declared special member functions.
2631 class ImplicitExceptionSpecification {
2632 ASTContext &Context;
2633 bool AllowsAllExceptions;
2634 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2635 llvm::SmallVector<QualType, 4> Exceptions;
2636
2637 public:
2638 explicit ImplicitExceptionSpecification(ASTContext &Context)
2639 : Context(Context), AllowsAllExceptions(false) { }
2640
2641 /// \brief Whether the special member function should have any
2642 /// exception specification at all.
2643 bool hasExceptionSpecification() const {
2644 return !AllowsAllExceptions;
2645 }
2646
2647 /// \brief Whether the special member function should have a
2648 /// throw(...) exception specification (a Microsoft extension).
2649 bool hasAnyExceptionSpecification() const {
2650 return false;
2651 }
2652
2653 /// \brief The number of exceptions in the exception specification.
2654 unsigned size() const { return Exceptions.size(); }
2655
2656 /// \brief The set of exceptions in the exception specification.
2657 const QualType *data() const { return Exceptions.data(); }
2658
2659 /// \brief Note that
2660 void CalledDecl(CXXMethodDecl *Method) {
2661 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002662 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002663 return;
2664
2665 const FunctionProtoType *Proto
2666 = Method->getType()->getAs<FunctionProtoType>();
2667
2668 // If this function can throw any exceptions, make a note of that.
2669 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2670 AllowsAllExceptions = true;
2671 ExceptionsSeen.clear();
2672 Exceptions.clear();
2673 return;
2674 }
2675
2676 // Record the exceptions in this function's exception specification.
2677 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2678 EEnd = Proto->exception_end();
2679 E != EEnd; ++E)
2680 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2681 Exceptions.push_back(*E);
2682 }
2683 };
2684}
2685
2686
Douglas Gregor05379422008-11-03 17:51:48 +00002687/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2688/// special functions, such as the default constructor, copy
2689/// constructor, or destructor, to the given C++ class (C++
2690/// [special]p1). This routine can only be executed just before the
2691/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002692void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002693 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002694 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002695
Douglas Gregor54be3392010-07-01 17:57:27 +00002696 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002697 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002698
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002699 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2700 ++ASTContext::NumImplicitCopyAssignmentOperators;
2701
2702 // If we have a dynamic class, then the copy assignment operator may be
2703 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2704 // it shows up in the right place in the vtable and that we diagnose
2705 // problems with the implicit exception specification.
2706 if (ClassDecl->isDynamicClass())
2707 DeclareImplicitCopyAssignment(ClassDecl);
2708 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002709
Douglas Gregor7454c562010-07-02 20:37:36 +00002710 if (!ClassDecl->hasUserDeclaredDestructor()) {
2711 ++ASTContext::NumImplicitDestructors;
2712
2713 // If we have a dynamic class, then the destructor may be virtual, so we
2714 // have to declare the destructor immediately. This ensures that, e.g., it
2715 // shows up in the right place in the vtable and that we diagnose problems
2716 // with the implicit exception specification.
2717 if (ClassDecl->isDynamicClass())
2718 DeclareImplicitDestructor(ClassDecl);
2719 }
Douglas Gregor05379422008-11-03 17:51:48 +00002720}
2721
John McCall48871652010-08-21 09:40:31 +00002722void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002723 if (!D)
2724 return;
2725
2726 TemplateParameterList *Params = 0;
2727 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2728 Params = Template->getTemplateParameters();
2729 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2730 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2731 Params = PartialSpec->getTemplateParameters();
2732 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002733 return;
2734
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002735 for (TemplateParameterList::iterator Param = Params->begin(),
2736 ParamEnd = Params->end();
2737 Param != ParamEnd; ++Param) {
2738 NamedDecl *Named = cast<NamedDecl>(*Param);
2739 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002740 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002741 IdResolver.AddDecl(Named);
2742 }
2743 }
2744}
2745
John McCall48871652010-08-21 09:40:31 +00002746void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002747 if (!RecordD) return;
2748 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002749 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002750 PushDeclContext(S, Record);
2751}
2752
John McCall48871652010-08-21 09:40:31 +00002753void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002754 if (!RecordD) return;
2755 PopDeclContext();
2756}
2757
Douglas Gregor4d87df52008-12-16 21:30:33 +00002758/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2759/// parsing a top-level (non-nested) C++ class, and we are now
2760/// parsing those parts of the given Method declaration that could
2761/// not be parsed earlier (C++ [class.mem]p2), such as default
2762/// arguments. This action should enter the scope of the given
2763/// Method declaration as if we had just parsed the qualified method
2764/// name. However, it should not bring the parameters into scope;
2765/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002766void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002767}
2768
2769/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2770/// C++ method declaration. We're (re-)introducing the given
2771/// function parameter into scope for use in parsing later parts of
2772/// the method declaration. For example, we could see an
2773/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002774void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002775 if (!ParamD)
2776 return;
Mike Stump11289f42009-09-09 15:08:12 +00002777
John McCall48871652010-08-21 09:40:31 +00002778 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002779
2780 // If this parameter has an unparsed default argument, clear it out
2781 // to make way for the parsed default argument.
2782 if (Param->hasUnparsedDefaultArg())
2783 Param->setDefaultArg(0);
2784
John McCall48871652010-08-21 09:40:31 +00002785 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002786 if (Param->getDeclName())
2787 IdResolver.AddDecl(Param);
2788}
2789
2790/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2791/// processing the delayed method declaration for Method. The method
2792/// declaration is now considered finished. There may be a separate
2793/// ActOnStartOfFunctionDef action later (not necessarily
2794/// immediately!) for this method, if it was also defined inside the
2795/// class body.
John McCall48871652010-08-21 09:40:31 +00002796void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002797 if (!MethodD)
2798 return;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002800 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002801
John McCall48871652010-08-21 09:40:31 +00002802 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002803
2804 // Now that we have our default arguments, check the constructor
2805 // again. It could produce additional diagnostics or affect whether
2806 // the class has implicitly-declared destructors, among other
2807 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002808 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2809 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002810
2811 // Check the default arguments, which we may have added.
2812 if (!Method->isInvalidDecl())
2813 CheckCXXDefaultArguments(Method);
2814}
2815
Douglas Gregor831c93f2008-11-05 20:51:48 +00002816/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002817/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002818/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002819/// emit diagnostics and set the invalid bit to true. In any case, the type
2820/// will be updated to reflect a well-formed type for the constructor and
2821/// returned.
2822QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002823 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002824 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002825
2826 // C++ [class.ctor]p3:
2827 // A constructor shall not be virtual (10.3) or static (9.4). A
2828 // constructor can be invoked for a const, volatile or const
2829 // volatile object. A constructor shall not be declared const,
2830 // volatile, or const volatile (9.3.2).
2831 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002832 if (!D.isInvalidType())
2833 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2834 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2835 << SourceRange(D.getIdentifierLoc());
2836 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002837 }
John McCall8e7d6562010-08-26 03:08:43 +00002838 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002839 if (!D.isInvalidType())
2840 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2841 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2842 << SourceRange(D.getIdentifierLoc());
2843 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002844 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002845 }
Mike Stump11289f42009-09-09 15:08:12 +00002846
Chris Lattner38378bf2009-04-25 08:28:21 +00002847 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2848 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002849 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002850 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2851 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002852 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002853 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2854 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002855 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002856 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2857 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002858 }
Mike Stump11289f42009-09-09 15:08:12 +00002859
Douglas Gregor831c93f2008-11-05 20:51:48 +00002860 // Rebuild the function type "R" without any type qualifiers (in
2861 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002862 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002863 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002864 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2865 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002866 Proto->isVariadic(), 0,
2867 Proto->hasExceptionSpec(),
2868 Proto->hasAnyExceptionSpec(),
2869 Proto->getNumExceptions(),
2870 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002871 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002872}
2873
Douglas Gregor4d87df52008-12-16 21:30:33 +00002874/// CheckConstructor - Checks a fully-formed constructor for
2875/// well-formedness, issuing any diagnostics required. Returns true if
2876/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002877void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002878 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002879 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2880 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002881 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002882
2883 // C++ [class.copy]p3:
2884 // A declaration of a constructor for a class X is ill-formed if
2885 // its first parameter is of type (optionally cv-qualified) X and
2886 // either there are no other parameters or else all other
2887 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002888 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002889 ((Constructor->getNumParams() == 1) ||
2890 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002891 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2892 Constructor->getTemplateSpecializationKind()
2893 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002894 QualType ParamType = Constructor->getParamDecl(0)->getType();
2895 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2896 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002897 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002898 const char *ConstRef
2899 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2900 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002901 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002902 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002903
2904 // FIXME: Rather that making the constructor invalid, we should endeavor
2905 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002906 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002907 }
2908 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002909}
2910
John McCalldeb646e2010-08-04 01:04:25 +00002911/// CheckDestructor - Checks a fully-formed destructor definition for
2912/// well-formedness, issuing any diagnostics required. Returns true
2913/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002914bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002915 CXXRecordDecl *RD = Destructor->getParent();
2916
2917 if (Destructor->isVirtual()) {
2918 SourceLocation Loc;
2919
2920 if (!Destructor->isImplicit())
2921 Loc = Destructor->getLocation();
2922 else
2923 Loc = RD->getLocation();
2924
2925 // If we have a virtual destructor, look up the deallocation function
2926 FunctionDecl *OperatorDelete = 0;
2927 DeclarationName Name =
2928 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002929 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002930 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002931
2932 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002933
2934 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002935 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002936
2937 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002938}
2939
Mike Stump11289f42009-09-09 15:08:12 +00002940static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002941FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2942 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2943 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002944 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002945}
2946
Douglas Gregor831c93f2008-11-05 20:51:48 +00002947/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2948/// the well-formednes of the destructor declarator @p D with type @p
2949/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002950/// emit diagnostics and set the declarator to invalid. Even if this happens,
2951/// will be updated to reflect a well-formed type for the destructor and
2952/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002953QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002954 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002955 // C++ [class.dtor]p1:
2956 // [...] A typedef-name that names a class is a class-name
2957 // (7.1.3); however, a typedef-name that names a class shall not
2958 // be used as the identifier in the declarator for a destructor
2959 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002960 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002961 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002962 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002963 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002964
2965 // C++ [class.dtor]p2:
2966 // A destructor is used to destroy objects of its class type. A
2967 // destructor takes no parameters, and no return type can be
2968 // specified for it (not even void). The address of a destructor
2969 // shall not be taken. A destructor shall not be static. A
2970 // destructor can be invoked for a const, volatile or const
2971 // volatile object. A destructor shall not be declared const,
2972 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002973 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002974 if (!D.isInvalidType())
2975 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2976 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002977 << SourceRange(D.getIdentifierLoc())
2978 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2979
John McCall8e7d6562010-08-26 03:08:43 +00002980 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002981 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002982 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002983 // Destructors don't have return types, but the parser will
2984 // happily parse something like:
2985 //
2986 // class X {
2987 // float ~X();
2988 // };
2989 //
2990 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002991 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2992 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2993 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002994 }
Mike Stump11289f42009-09-09 15:08:12 +00002995
Chris Lattner38378bf2009-04-25 08:28:21 +00002996 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2997 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002998 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3000 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003001 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003002 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3003 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003004 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3006 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003007 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003008 }
3009
3010 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003011 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003012 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3013
3014 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003015 FTI.freeArgs();
3016 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003017 }
3018
Mike Stump11289f42009-09-09 15:08:12 +00003019 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003020 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003021 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003022 D.setInvalidType();
3023 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003024
3025 // Rebuild the function type "R" without any type qualifiers or
3026 // parameters (in case any of the errors above fired) and with
3027 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003028 // types.
3029 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3030 if (!Proto)
3031 return QualType();
3032
Douglas Gregor36c569f2010-02-21 22:15:06 +00003033 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00003034 Proto->hasExceptionSpec(),
3035 Proto->hasAnyExceptionSpec(),
3036 Proto->getNumExceptions(),
3037 Proto->exception_begin(),
3038 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003039}
3040
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003041/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3042/// well-formednes of the conversion function declarator @p D with
3043/// type @p R. If there are any errors in the declarator, this routine
3044/// will emit diagnostics and return true. Otherwise, it will return
3045/// false. Either way, the type @p R will be updated to reflect a
3046/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003047void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003048 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003049 // C++ [class.conv.fct]p1:
3050 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003051 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003052 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003053 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003054 if (!D.isInvalidType())
3055 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3056 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3057 << SourceRange(D.getIdentifierLoc());
3058 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003059 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003060 }
John McCall212fa2e2010-04-13 00:04:31 +00003061
3062 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3063
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003064 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003065 // Conversion functions don't have return types, but the parser will
3066 // happily parse something like:
3067 //
3068 // class X {
3069 // float operator bool();
3070 // };
3071 //
3072 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003073 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3074 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3075 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003076 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003077 }
3078
John McCall212fa2e2010-04-13 00:04:31 +00003079 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3080
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003081 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003082 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003083 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3084
3085 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003086 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003087 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003088 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003089 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003090 D.setInvalidType();
3091 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003092
John McCall212fa2e2010-04-13 00:04:31 +00003093 // Diagnose "&operator bool()" and other such nonsense. This
3094 // is actually a gcc extension which we don't support.
3095 if (Proto->getResultType() != ConvType) {
3096 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3097 << Proto->getResultType();
3098 D.setInvalidType();
3099 ConvType = Proto->getResultType();
3100 }
3101
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003102 // C++ [class.conv.fct]p4:
3103 // The conversion-type-id shall not represent a function type nor
3104 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003105 if (ConvType->isArrayType()) {
3106 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3107 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003108 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003109 } else if (ConvType->isFunctionType()) {
3110 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3111 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003112 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003113 }
3114
3115 // Rebuild the function type "R" without any parameters (in case any
3116 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003117 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003118 if (D.isInvalidType()) {
3119 R = Context.getFunctionType(ConvType, 0, 0, false,
3120 Proto->getTypeQuals(),
3121 Proto->hasExceptionSpec(),
3122 Proto->hasAnyExceptionSpec(),
3123 Proto->getNumExceptions(),
3124 Proto->exception_begin(),
3125 Proto->getExtInfo());
3126 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003127
Douglas Gregor5fb53972009-01-14 15:45:31 +00003128 // C++0x explicit conversion operators.
3129 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003130 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003131 diag::warn_explicit_conversion_functions)
3132 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003133}
3134
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003135/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3136/// the declaration of the given C++ conversion function. This routine
3137/// is responsible for recording the conversion function in the C++
3138/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003139Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003140 assert(Conversion && "Expected to receive a conversion function declaration");
3141
Douglas Gregor4287b372008-12-12 08:25:50 +00003142 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003143
3144 // Make sure we aren't redeclaring the conversion function.
3145 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003146
3147 // C++ [class.conv.fct]p1:
3148 // [...] A conversion function is never used to convert a
3149 // (possibly cv-qualified) object to the (possibly cv-qualified)
3150 // same object type (or a reference to it), to a (possibly
3151 // cv-qualified) base class of that type (or a reference to it),
3152 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003153 // FIXME: Suppress this warning if the conversion function ends up being a
3154 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003155 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003156 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003157 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003158 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003159 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3160 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003161 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003162 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003163 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3164 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003165 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003166 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003167 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003168 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003169 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003170 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003171 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003172 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173 }
3174
Douglas Gregor457104e2010-09-29 04:25:11 +00003175 if (FunctionTemplateDecl *ConversionTemplate
3176 = Conversion->getDescribedFunctionTemplate())
3177 return ConversionTemplate;
3178
John McCall48871652010-08-21 09:40:31 +00003179 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003180}
3181
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003182//===----------------------------------------------------------------------===//
3183// Namespace Handling
3184//===----------------------------------------------------------------------===//
3185
John McCallb1be5232010-08-26 09:15:37 +00003186
3187
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003188/// ActOnStartNamespaceDef - This is called at the start of a namespace
3189/// definition.
John McCall48871652010-08-21 09:40:31 +00003190Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003191 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003192 SourceLocation IdentLoc,
3193 IdentifierInfo *II,
3194 SourceLocation LBrace,
3195 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003196 // anonymous namespace starts at its left brace
3197 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3198 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003199 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003200 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003201
3202 Scope *DeclRegionScope = NamespcScope->getParent();
3203
Anders Carlssona7bcade2010-02-07 01:09:23 +00003204 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3205
Eli Friedman570024a2010-08-05 06:57:20 +00003206 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallb1be5232010-08-26 09:15:37 +00003207 PushVisibilityAttr(attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003208
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003209 if (II) {
3210 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003211 // The identifier in an original-namespace-definition shall not
3212 // have been previously defined in the declarative region in
3213 // which the original-namespace-definition appears. The
3214 // identifier in an original-namespace-definition is the name of
3215 // the namespace. Subsequently in that declarative region, it is
3216 // treated as an original-namespace-name.
3217 //
3218 // Since namespace names are unique in their scope, and we don't
3219 // look through using directives, just
3220 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3221 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003222
Douglas Gregor91f84212008-12-11 16:49:14 +00003223 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3224 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003225 if (Namespc->isInline() != OrigNS->isInline()) {
3226 // inline-ness must match
3227 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3228 << Namespc->isInline();
3229 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3230 Namespc->setInvalidDecl();
3231 // Recover by ignoring the new namespace's inline status.
3232 Namespc->setInline(OrigNS->isInline());
3233 }
3234
Douglas Gregor91f84212008-12-11 16:49:14 +00003235 // Attach this namespace decl to the chain of extended namespace
3236 // definitions.
3237 OrigNS->setNextNamespace(Namespc);
3238 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003239
Mike Stump11289f42009-09-09 15:08:12 +00003240 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003241 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003242 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003243 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003244 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003245 } else if (PrevDecl) {
3246 // This is an invalid name redefinition.
3247 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3248 << Namespc->getDeclName();
3249 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3250 Namespc->setInvalidDecl();
3251 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003252 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003253 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003254 // This is the first "real" definition of the namespace "std", so update
3255 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003256 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003257 // We had already defined a dummy namespace "std". Link this new
3258 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003259 StdNS->setNextNamespace(Namespc);
3260 StdNS->setLocation(IdentLoc);
3261 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003262 }
3263
3264 // Make our StdNamespace cache point at the first real definition of the
3265 // "std" namespace.
3266 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003267 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003268
3269 PushOnScopeChains(Namespc, DeclRegionScope);
3270 } else {
John McCall4fa53422009-10-01 00:25:31 +00003271 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003272 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003273
3274 // Link the anonymous namespace into its parent.
3275 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003276 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003277 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3278 PrevDecl = TU->getAnonymousNamespace();
3279 TU->setAnonymousNamespace(Namespc);
3280 } else {
3281 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3282 PrevDecl = ND->getAnonymousNamespace();
3283 ND->setAnonymousNamespace(Namespc);
3284 }
3285
3286 // Link the anonymous namespace with its previous declaration.
3287 if (PrevDecl) {
3288 assert(PrevDecl->isAnonymousNamespace());
3289 assert(!PrevDecl->getNextNamespace());
3290 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3291 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003292
3293 if (Namespc->isInline() != PrevDecl->isInline()) {
3294 // inline-ness must match
3295 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3296 << Namespc->isInline();
3297 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3298 Namespc->setInvalidDecl();
3299 // Recover by ignoring the new namespace's inline status.
3300 Namespc->setInline(PrevDecl->isInline());
3301 }
John McCall0db42252009-12-16 02:06:49 +00003302 }
John McCall4fa53422009-10-01 00:25:31 +00003303
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003304 CurContext->addDecl(Namespc);
3305
John McCall4fa53422009-10-01 00:25:31 +00003306 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3307 // behaves as if it were replaced by
3308 // namespace unique { /* empty body */ }
3309 // using namespace unique;
3310 // namespace unique { namespace-body }
3311 // where all occurrences of 'unique' in a translation unit are
3312 // replaced by the same identifier and this identifier differs
3313 // from all other identifiers in the entire program.
3314
3315 // We just create the namespace with an empty name and then add an
3316 // implicit using declaration, just like the standard suggests.
3317 //
3318 // CodeGen enforces the "universally unique" aspect by giving all
3319 // declarations semantically contained within an anonymous
3320 // namespace internal linkage.
3321
John McCall0db42252009-12-16 02:06:49 +00003322 if (!PrevDecl) {
3323 UsingDirectiveDecl* UD
3324 = UsingDirectiveDecl::Create(Context, CurContext,
3325 /* 'using' */ LBrace,
3326 /* 'namespace' */ SourceLocation(),
3327 /* qualifier */ SourceRange(),
3328 /* NNS */ NULL,
3329 /* identifier */ SourceLocation(),
3330 Namespc,
3331 /* Ancestor */ CurContext);
3332 UD->setImplicit();
3333 CurContext->addDecl(UD);
3334 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003335 }
3336
3337 // Although we could have an invalid decl (i.e. the namespace name is a
3338 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003339 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3340 // for the namespace has the declarations that showed up in that particular
3341 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003342 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003343 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003344}
3345
Sebastian Redla6602e92009-11-23 15:34:23 +00003346/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3347/// is a namespace alias, returns the namespace it points to.
3348static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3349 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3350 return AD->getNamespace();
3351 return dyn_cast_or_null<NamespaceDecl>(D);
3352}
3353
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003354/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3355/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003356void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003357 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3358 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3359 Namespc->setRBracLoc(RBrace);
3360 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003361 if (Namespc->hasAttr<VisibilityAttr>())
3362 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003363}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003364
John McCall28a0cf72010-08-25 07:42:41 +00003365CXXRecordDecl *Sema::getStdBadAlloc() const {
3366 return cast_or_null<CXXRecordDecl>(
3367 StdBadAlloc.get(Context.getExternalSource()));
3368}
3369
3370NamespaceDecl *Sema::getStdNamespace() const {
3371 return cast_or_null<NamespaceDecl>(
3372 StdNamespace.get(Context.getExternalSource()));
3373}
3374
Douglas Gregorcdf87022010-06-29 17:53:46 +00003375/// \brief Retrieve the special "std" namespace, which may require us to
3376/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003377NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003378 if (!StdNamespace) {
3379 // The "std" namespace has not yet been defined, so build one implicitly.
3380 StdNamespace = NamespaceDecl::Create(Context,
3381 Context.getTranslationUnitDecl(),
3382 SourceLocation(),
3383 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003384 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003385 }
3386
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003387 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003388}
3389
John McCall48871652010-08-21 09:40:31 +00003390Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003391 SourceLocation UsingLoc,
3392 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003393 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003394 SourceLocation IdentLoc,
3395 IdentifierInfo *NamespcName,
3396 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003397 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3398 assert(NamespcName && "Invalid NamespcName.");
3399 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003400 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003401
Douglas Gregor889ceb72009-02-03 19:21:40 +00003402 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003403 NestedNameSpecifier *Qualifier = 0;
3404 if (SS.isSet())
3405 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3406
Douglas Gregor34074322009-01-14 22:20:51 +00003407 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003408 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3409 LookupParsedName(R, S, &SS);
3410 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003411 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003412
Douglas Gregorcdf87022010-06-29 17:53:46 +00003413 if (R.empty()) {
3414 // Allow "using namespace std;" or "using namespace ::std;" even if
3415 // "std" hasn't been defined yet, for GCC compatibility.
3416 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3417 NamespcName->isStr("std")) {
3418 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003419 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003420 R.resolveKind();
3421 }
3422 // Otherwise, attempt typo correction.
3423 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3424 CTC_NoKeywords, 0)) {
3425 if (R.getAsSingle<NamespaceDecl>() ||
3426 R.getAsSingle<NamespaceAliasDecl>()) {
3427 if (DeclContext *DC = computeDeclContext(SS, false))
3428 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3429 << NamespcName << DC << Corrected << SS.getRange()
3430 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3431 else
3432 Diag(IdentLoc, diag::err_using_directive_suggest)
3433 << NamespcName << Corrected
3434 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3435 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3436 << Corrected;
3437
3438 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003439 } else {
3440 R.clear();
3441 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003442 }
3443 }
3444 }
3445
John McCall9f3059a2009-10-09 21:13:30 +00003446 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003447 NamedDecl *Named = R.getFoundDecl();
3448 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3449 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003450 // C++ [namespace.udir]p1:
3451 // A using-directive specifies that the names in the nominated
3452 // namespace can be used in the scope in which the
3453 // using-directive appears after the using-directive. During
3454 // unqualified name lookup (3.4.1), the names appear as if they
3455 // were declared in the nearest enclosing namespace which
3456 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003457 // namespace. [Note: in this context, "contains" means "contains
3458 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003459
3460 // Find enclosing context containing both using-directive and
3461 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003462 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003463 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3464 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3465 CommonAncestor = CommonAncestor->getParent();
3466
Sebastian Redla6602e92009-11-23 15:34:23 +00003467 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003468 SS.getRange(),
3469 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003470 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003471 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003472 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003473 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003474 }
3475
Douglas Gregor889ceb72009-02-03 19:21:40 +00003476 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003477 delete AttrList;
John McCall48871652010-08-21 09:40:31 +00003478 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003479}
3480
3481void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3482 // If scope has associated entity, then using directive is at namespace
3483 // or translation unit scope. We add UsingDirectiveDecls, into
3484 // it's lookup structure.
3485 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003486 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003487 else
3488 // Otherwise it is block-sope. using-directives will affect lookup
3489 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003490 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003491}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003492
Douglas Gregorfec52632009-06-20 00:51:54 +00003493
John McCall48871652010-08-21 09:40:31 +00003494Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003495 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003496 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003497 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003498 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003499 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003500 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003501 bool IsTypeName,
3502 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003503 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003504
Douglas Gregor220f4272009-11-04 16:30:06 +00003505 switch (Name.getKind()) {
3506 case UnqualifiedId::IK_Identifier:
3507 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003508 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003509 case UnqualifiedId::IK_ConversionFunctionId:
3510 break;
3511
3512 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003513 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003514 // C++0x inherited constructors.
3515 if (getLangOptions().CPlusPlus0x) break;
3516
Douglas Gregor220f4272009-11-04 16:30:06 +00003517 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3518 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003519 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003520
3521 case UnqualifiedId::IK_DestructorName:
3522 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3523 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003524 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003525
3526 case UnqualifiedId::IK_TemplateId:
3527 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3528 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003529 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003530 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003531
3532 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3533 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003534 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003535 return 0;
John McCall3969e302009-12-08 07:46:18 +00003536
John McCalla0097262009-12-11 02:10:03 +00003537 // Warn about using declarations.
3538 // TODO: store that the declaration was written without 'using' and
3539 // talk about access decls instead of using decls in the
3540 // diagnostics.
3541 if (!HasUsingKeyword) {
3542 UsingLoc = Name.getSourceRange().getBegin();
3543
3544 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003545 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003546 }
3547
John McCall3f746822009-11-17 05:59:44 +00003548 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003549 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003550 /* IsInstantiation */ false,
3551 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003552 if (UD)
3553 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003554
John McCall48871652010-08-21 09:40:31 +00003555 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003556}
3557
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003558/// \brief Determine whether a using declaration considers the given
3559/// declarations as "equivalent", e.g., if they are redeclarations of
3560/// the same entity or are both typedefs of the same type.
3561static bool
3562IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3563 bool &SuppressRedeclaration) {
3564 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3565 SuppressRedeclaration = false;
3566 return true;
3567 }
3568
3569 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3570 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3571 SuppressRedeclaration = true;
3572 return Context.hasSameType(TD1->getUnderlyingType(),
3573 TD2->getUnderlyingType());
3574 }
3575
3576 return false;
3577}
3578
3579
John McCall84d87672009-12-10 09:41:52 +00003580/// Determines whether to create a using shadow decl for a particular
3581/// decl, given the set of decls existing prior to this using lookup.
3582bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3583 const LookupResult &Previous) {
3584 // Diagnose finding a decl which is not from a base class of the
3585 // current class. We do this now because there are cases where this
3586 // function will silently decide not to build a shadow decl, which
3587 // will pre-empt further diagnostics.
3588 //
3589 // We don't need to do this in C++0x because we do the check once on
3590 // the qualifier.
3591 //
3592 // FIXME: diagnose the following if we care enough:
3593 // struct A { int foo; };
3594 // struct B : A { using A::foo; };
3595 // template <class T> struct C : A {};
3596 // template <class T> struct D : C<T> { using B::foo; } // <---
3597 // This is invalid (during instantiation) in C++03 because B::foo
3598 // resolves to the using decl in B, which is not a base class of D<T>.
3599 // We can't diagnose it immediately because C<T> is an unknown
3600 // specialization. The UsingShadowDecl in D<T> then points directly
3601 // to A::foo, which will look well-formed when we instantiate.
3602 // The right solution is to not collapse the shadow-decl chain.
3603 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3604 DeclContext *OrigDC = Orig->getDeclContext();
3605
3606 // Handle enums and anonymous structs.
3607 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3608 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3609 while (OrigRec->isAnonymousStructOrUnion())
3610 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3611
3612 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3613 if (OrigDC == CurContext) {
3614 Diag(Using->getLocation(),
3615 diag::err_using_decl_nested_name_specifier_is_current_class)
3616 << Using->getNestedNameRange();
3617 Diag(Orig->getLocation(), diag::note_using_decl_target);
3618 return true;
3619 }
3620
3621 Diag(Using->getNestedNameRange().getBegin(),
3622 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3623 << Using->getTargetNestedNameDecl()
3624 << cast<CXXRecordDecl>(CurContext)
3625 << Using->getNestedNameRange();
3626 Diag(Orig->getLocation(), diag::note_using_decl_target);
3627 return true;
3628 }
3629 }
3630
3631 if (Previous.empty()) return false;
3632
3633 NamedDecl *Target = Orig;
3634 if (isa<UsingShadowDecl>(Target))
3635 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3636
John McCalla17e83e2009-12-11 02:33:26 +00003637 // If the target happens to be one of the previous declarations, we
3638 // don't have a conflict.
3639 //
3640 // FIXME: but we might be increasing its access, in which case we
3641 // should redeclare it.
3642 NamedDecl *NonTag = 0, *Tag = 0;
3643 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3644 I != E; ++I) {
3645 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003646 bool Result;
3647 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3648 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003649
3650 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3651 }
3652
John McCall84d87672009-12-10 09:41:52 +00003653 if (Target->isFunctionOrFunctionTemplate()) {
3654 FunctionDecl *FD;
3655 if (isa<FunctionTemplateDecl>(Target))
3656 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3657 else
3658 FD = cast<FunctionDecl>(Target);
3659
3660 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003661 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003662 case Ovl_Overload:
3663 return false;
3664
3665 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003666 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003667 break;
3668
3669 // We found a decl with the exact signature.
3670 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003671 // If we're in a record, we want to hide the target, so we
3672 // return true (without a diagnostic) to tell the caller not to
3673 // build a shadow decl.
3674 if (CurContext->isRecord())
3675 return true;
3676
3677 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003678 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003679 break;
3680 }
3681
3682 Diag(Target->getLocation(), diag::note_using_decl_target);
3683 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3684 return true;
3685 }
3686
3687 // Target is not a function.
3688
John McCall84d87672009-12-10 09:41:52 +00003689 if (isa<TagDecl>(Target)) {
3690 // No conflict between a tag and a non-tag.
3691 if (!Tag) return false;
3692
John McCalle29c5cd2009-12-10 19:51:03 +00003693 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003694 Diag(Target->getLocation(), diag::note_using_decl_target);
3695 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3696 return true;
3697 }
3698
3699 // No conflict between a tag and a non-tag.
3700 if (!NonTag) return false;
3701
John McCalle29c5cd2009-12-10 19:51:03 +00003702 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003703 Diag(Target->getLocation(), diag::note_using_decl_target);
3704 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3705 return true;
3706}
3707
John McCall3f746822009-11-17 05:59:44 +00003708/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003709UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003710 UsingDecl *UD,
3711 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003712
3713 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003714 NamedDecl *Target = Orig;
3715 if (isa<UsingShadowDecl>(Target)) {
3716 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3717 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003718 }
3719
3720 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003721 = UsingShadowDecl::Create(Context, CurContext,
3722 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003723 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003724
3725 Shadow->setAccess(UD->getAccess());
3726 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3727 Shadow->setInvalidDecl();
3728
John McCall3f746822009-11-17 05:59:44 +00003729 if (S)
John McCall3969e302009-12-08 07:46:18 +00003730 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003731 else
John McCall3969e302009-12-08 07:46:18 +00003732 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003733
John McCall3969e302009-12-08 07:46:18 +00003734
John McCall84d87672009-12-10 09:41:52 +00003735 return Shadow;
3736}
John McCall3969e302009-12-08 07:46:18 +00003737
John McCall84d87672009-12-10 09:41:52 +00003738/// Hides a using shadow declaration. This is required by the current
3739/// using-decl implementation when a resolvable using declaration in a
3740/// class is followed by a declaration which would hide or override
3741/// one or more of the using decl's targets; for example:
3742///
3743/// struct Base { void foo(int); };
3744/// struct Derived : Base {
3745/// using Base::foo;
3746/// void foo(int);
3747/// };
3748///
3749/// The governing language is C++03 [namespace.udecl]p12:
3750///
3751/// When a using-declaration brings names from a base class into a
3752/// derived class scope, member functions in the derived class
3753/// override and/or hide member functions with the same name and
3754/// parameter types in a base class (rather than conflicting).
3755///
3756/// There are two ways to implement this:
3757/// (1) optimistically create shadow decls when they're not hidden
3758/// by existing declarations, or
3759/// (2) don't create any shadow decls (or at least don't make them
3760/// visible) until we've fully parsed/instantiated the class.
3761/// The problem with (1) is that we might have to retroactively remove
3762/// a shadow decl, which requires several O(n) operations because the
3763/// decl structures are (very reasonably) not designed for removal.
3764/// (2) avoids this but is very fiddly and phase-dependent.
3765void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003766 if (Shadow->getDeclName().getNameKind() ==
3767 DeclarationName::CXXConversionFunctionName)
3768 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3769
John McCall84d87672009-12-10 09:41:52 +00003770 // Remove it from the DeclContext...
3771 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003772
John McCall84d87672009-12-10 09:41:52 +00003773 // ...and the scope, if applicable...
3774 if (S) {
John McCall48871652010-08-21 09:40:31 +00003775 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003776 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003777 }
3778
John McCall84d87672009-12-10 09:41:52 +00003779 // ...and the using decl.
3780 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3781
3782 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003783 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003784}
3785
John McCalle61f2ba2009-11-18 02:36:19 +00003786/// Builds a using declaration.
3787///
3788/// \param IsInstantiation - Whether this call arises from an
3789/// instantiation of an unresolved using declaration. We treat
3790/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003791NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3792 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003793 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003794 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003795 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003796 bool IsInstantiation,
3797 bool IsTypeName,
3798 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003799 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003800 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003801 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003802
Anders Carlssonf038fc22009-08-28 05:49:21 +00003803 // FIXME: We ignore attributes for now.
3804 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003805
Anders Carlsson59140b32009-08-28 03:16:11 +00003806 if (SS.isEmpty()) {
3807 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003808 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003809 }
Mike Stump11289f42009-09-09 15:08:12 +00003810
John McCall84d87672009-12-10 09:41:52 +00003811 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003812 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003813 ForRedeclaration);
3814 Previous.setHideTags(false);
3815 if (S) {
3816 LookupName(Previous, S);
3817
3818 // It is really dumb that we have to do this.
3819 LookupResult::Filter F = Previous.makeFilter();
3820 while (F.hasNext()) {
3821 NamedDecl *D = F.next();
3822 if (!isDeclInScope(D, CurContext, S))
3823 F.erase();
3824 }
3825 F.done();
3826 } else {
3827 assert(IsInstantiation && "no scope in non-instantiation");
3828 assert(CurContext->isRecord() && "scope not record in instantiation");
3829 LookupQualifiedName(Previous, CurContext);
3830 }
3831
Mike Stump11289f42009-09-09 15:08:12 +00003832 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003833 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3834
John McCall84d87672009-12-10 09:41:52 +00003835 // Check for invalid redeclarations.
3836 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3837 return 0;
3838
3839 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003840 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3841 return 0;
3842
John McCall84c16cf2009-11-12 03:15:40 +00003843 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003844 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003845 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003846 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003847 // FIXME: not all declaration name kinds are legal here
3848 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3849 UsingLoc, TypenameLoc,
3850 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003851 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003852 } else {
3853 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003854 UsingLoc, SS.getRange(),
3855 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003856 }
John McCallb96ec562009-12-04 22:46:56 +00003857 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003858 D = UsingDecl::Create(Context, CurContext,
3859 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003860 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003861 }
John McCallb96ec562009-12-04 22:46:56 +00003862 D->setAccess(AS);
3863 CurContext->addDecl(D);
3864
3865 if (!LookupContext) return D;
3866 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003867
John McCall0b66eb32010-05-01 00:40:08 +00003868 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003869 UD->setInvalidDecl();
3870 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003871 }
3872
John McCall3969e302009-12-08 07:46:18 +00003873 // Look up the target name.
3874
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003875 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003876
John McCall3969e302009-12-08 07:46:18 +00003877 // Unlike most lookups, we don't always want to hide tag
3878 // declarations: tag names are visible through the using declaration
3879 // even if hidden by ordinary names, *except* in a dependent context
3880 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003881 if (!IsInstantiation)
3882 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003883
John McCall27b18f82009-11-17 02:14:36 +00003884 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003885
John McCall9f3059a2009-10-09 21:13:30 +00003886 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003887 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003888 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003889 UD->setInvalidDecl();
3890 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003891 }
3892
John McCallb96ec562009-12-04 22:46:56 +00003893 if (R.isAmbiguous()) {
3894 UD->setInvalidDecl();
3895 return UD;
3896 }
Mike Stump11289f42009-09-09 15:08:12 +00003897
John McCalle61f2ba2009-11-18 02:36:19 +00003898 if (IsTypeName) {
3899 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003900 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003901 Diag(IdentLoc, diag::err_using_typename_non_type);
3902 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3903 Diag((*I)->getUnderlyingDecl()->getLocation(),
3904 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003905 UD->setInvalidDecl();
3906 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003907 }
3908 } else {
3909 // If we asked for a non-typename and we got a type, error out,
3910 // but only if this is an instantiation of an unresolved using
3911 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003912 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003913 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3914 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003915 UD->setInvalidDecl();
3916 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003917 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003918 }
3919
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003920 // C++0x N2914 [namespace.udecl]p6:
3921 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003922 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003923 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3924 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003925 UD->setInvalidDecl();
3926 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003927 }
Mike Stump11289f42009-09-09 15:08:12 +00003928
John McCall84d87672009-12-10 09:41:52 +00003929 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3930 if (!CheckUsingShadowDecl(UD, *I, Previous))
3931 BuildUsingShadowDecl(S, UD, *I);
3932 }
John McCall3f746822009-11-17 05:59:44 +00003933
3934 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003935}
3936
John McCall84d87672009-12-10 09:41:52 +00003937/// Checks that the given using declaration is not an invalid
3938/// redeclaration. Note that this is checking only for the using decl
3939/// itself, not for any ill-formedness among the UsingShadowDecls.
3940bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3941 bool isTypeName,
3942 const CXXScopeSpec &SS,
3943 SourceLocation NameLoc,
3944 const LookupResult &Prev) {
3945 // C++03 [namespace.udecl]p8:
3946 // C++0x [namespace.udecl]p10:
3947 // A using-declaration is a declaration and can therefore be used
3948 // repeatedly where (and only where) multiple declarations are
3949 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003950 //
3951 // That's in non-member contexts.
Sebastian Redl50c68252010-08-31 00:36:30 +00003952 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003953 return false;
3954
3955 NestedNameSpecifier *Qual
3956 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3957
3958 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3959 NamedDecl *D = *I;
3960
3961 bool DTypename;
3962 NestedNameSpecifier *DQual;
3963 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3964 DTypename = UD->isTypeName();
3965 DQual = UD->getTargetNestedNameDecl();
3966 } else if (UnresolvedUsingValueDecl *UD
3967 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3968 DTypename = false;
3969 DQual = UD->getTargetNestedNameSpecifier();
3970 } else if (UnresolvedUsingTypenameDecl *UD
3971 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3972 DTypename = true;
3973 DQual = UD->getTargetNestedNameSpecifier();
3974 } else continue;
3975
3976 // using decls differ if one says 'typename' and the other doesn't.
3977 // FIXME: non-dependent using decls?
3978 if (isTypeName != DTypename) continue;
3979
3980 // using decls differ if they name different scopes (but note that
3981 // template instantiation can cause this check to trigger when it
3982 // didn't before instantiation).
3983 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3984 Context.getCanonicalNestedNameSpecifier(DQual))
3985 continue;
3986
3987 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003988 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003989 return true;
3990 }
3991
3992 return false;
3993}
3994
John McCall3969e302009-12-08 07:46:18 +00003995
John McCallb96ec562009-12-04 22:46:56 +00003996/// Checks that the given nested-name qualifier used in a using decl
3997/// in the current context is appropriately related to the current
3998/// scope. If an error is found, diagnoses it and returns true.
3999bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4000 const CXXScopeSpec &SS,
4001 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004002 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004003
John McCall3969e302009-12-08 07:46:18 +00004004 if (!CurContext->isRecord()) {
4005 // C++03 [namespace.udecl]p3:
4006 // C++0x [namespace.udecl]p8:
4007 // A using-declaration for a class member shall be a member-declaration.
4008
4009 // If we weren't able to compute a valid scope, it must be a
4010 // dependent class scope.
4011 if (!NamedContext || NamedContext->isRecord()) {
4012 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4013 << SS.getRange();
4014 return true;
4015 }
4016
4017 // Otherwise, everything is known to be fine.
4018 return false;
4019 }
4020
4021 // The current scope is a record.
4022
4023 // If the named context is dependent, we can't decide much.
4024 if (!NamedContext) {
4025 // FIXME: in C++0x, we can diagnose if we can prove that the
4026 // nested-name-specifier does not refer to a base class, which is
4027 // still possible in some cases.
4028
4029 // Otherwise we have to conservatively report that things might be
4030 // okay.
4031 return false;
4032 }
4033
4034 if (!NamedContext->isRecord()) {
4035 // Ideally this would point at the last name in the specifier,
4036 // but we don't have that level of source info.
4037 Diag(SS.getRange().getBegin(),
4038 diag::err_using_decl_nested_name_specifier_is_not_class)
4039 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4040 return true;
4041 }
4042
4043 if (getLangOptions().CPlusPlus0x) {
4044 // C++0x [namespace.udecl]p3:
4045 // In a using-declaration used as a member-declaration, the
4046 // nested-name-specifier shall name a base class of the class
4047 // being defined.
4048
4049 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4050 cast<CXXRecordDecl>(NamedContext))) {
4051 if (CurContext == NamedContext) {
4052 Diag(NameLoc,
4053 diag::err_using_decl_nested_name_specifier_is_current_class)
4054 << SS.getRange();
4055 return true;
4056 }
4057
4058 Diag(SS.getRange().getBegin(),
4059 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4060 << (NestedNameSpecifier*) SS.getScopeRep()
4061 << cast<CXXRecordDecl>(CurContext)
4062 << SS.getRange();
4063 return true;
4064 }
4065
4066 return false;
4067 }
4068
4069 // C++03 [namespace.udecl]p4:
4070 // A using-declaration used as a member-declaration shall refer
4071 // to a member of a base class of the class being defined [etc.].
4072
4073 // Salient point: SS doesn't have to name a base class as long as
4074 // lookup only finds members from base classes. Therefore we can
4075 // diagnose here only if we can prove that that can't happen,
4076 // i.e. if the class hierarchies provably don't intersect.
4077
4078 // TODO: it would be nice if "definitely valid" results were cached
4079 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4080 // need to be repeated.
4081
4082 struct UserData {
4083 llvm::DenseSet<const CXXRecordDecl*> Bases;
4084
4085 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4086 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4087 Data->Bases.insert(Base);
4088 return true;
4089 }
4090
4091 bool hasDependentBases(const CXXRecordDecl *Class) {
4092 return !Class->forallBases(collect, this);
4093 }
4094
4095 /// Returns true if the base is dependent or is one of the
4096 /// accumulated base classes.
4097 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4098 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4099 return !Data->Bases.count(Base);
4100 }
4101
4102 bool mightShareBases(const CXXRecordDecl *Class) {
4103 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4104 }
4105 };
4106
4107 UserData Data;
4108
4109 // Returns false if we find a dependent base.
4110 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4111 return false;
4112
4113 // Returns false if the class has a dependent base or if it or one
4114 // of its bases is present in the base set of the current context.
4115 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4116 return false;
4117
4118 Diag(SS.getRange().getBegin(),
4119 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4120 << (NestedNameSpecifier*) SS.getScopeRep()
4121 << cast<CXXRecordDecl>(CurContext)
4122 << SS.getRange();
4123
4124 return true;
John McCallb96ec562009-12-04 22:46:56 +00004125}
4126
John McCall48871652010-08-21 09:40:31 +00004127Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004128 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004129 SourceLocation AliasLoc,
4130 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004131 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004132 SourceLocation IdentLoc,
4133 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004134
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004135 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004136 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4137 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004138
Anders Carlssondca83c42009-03-28 06:23:46 +00004139 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004140 NamedDecl *PrevDecl
4141 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4142 ForRedeclaration);
4143 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4144 PrevDecl = 0;
4145
4146 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004147 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004148 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004149 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004150 // FIXME: At some point, we'll want to create the (redundant)
4151 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004152 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004153 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004154 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004155 }
Mike Stump11289f42009-09-09 15:08:12 +00004156
Anders Carlssondca83c42009-03-28 06:23:46 +00004157 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4158 diag::err_redefinition_different_kind;
4159 Diag(AliasLoc, DiagID) << Alias;
4160 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004161 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004162 }
4163
John McCall27b18f82009-11-17 02:14:36 +00004164 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004165 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004166
John McCall9f3059a2009-10-09 21:13:30 +00004167 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004168 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4169 CTC_NoKeywords, 0)) {
4170 if (R.getAsSingle<NamespaceDecl>() ||
4171 R.getAsSingle<NamespaceAliasDecl>()) {
4172 if (DeclContext *DC = computeDeclContext(SS, false))
4173 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4174 << Ident << DC << Corrected << SS.getRange()
4175 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4176 else
4177 Diag(IdentLoc, diag::err_using_directive_suggest)
4178 << Ident << Corrected
4179 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4180
4181 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4182 << Corrected;
4183
4184 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004185 } else {
4186 R.clear();
4187 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004188 }
4189 }
4190
4191 if (R.empty()) {
4192 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004193 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004194 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004195 }
Mike Stump11289f42009-09-09 15:08:12 +00004196
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004197 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004198 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4199 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004200 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004201 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004202
John McCalld8d0d432010-02-16 06:53:13 +00004203 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004204 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004205}
4206
Douglas Gregora57478e2010-05-01 15:04:51 +00004207namespace {
4208 /// \brief Scoped object used to handle the state changes required in Sema
4209 /// to implicitly define the body of a C++ member function;
4210 class ImplicitlyDefinedFunctionScope {
4211 Sema &S;
4212 DeclContext *PreviousContext;
4213
4214 public:
4215 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4216 : S(S), PreviousContext(S.CurContext)
4217 {
4218 S.CurContext = Method;
4219 S.PushFunctionScope();
4220 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4221 }
4222
4223 ~ImplicitlyDefinedFunctionScope() {
4224 S.PopExpressionEvaluationContext();
4225 S.PopFunctionOrBlockScope();
4226 S.CurContext = PreviousContext;
4227 }
4228 };
4229}
4230
Sebastian Redlc15c3262010-09-13 22:02:47 +00004231static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4232 CXXRecordDecl *D) {
4233 ASTContext &Context = Self.Context;
4234 QualType ClassType = Context.getTypeDeclType(D);
4235 DeclarationName ConstructorName
4236 = Context.DeclarationNames.getCXXConstructorName(
4237 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4238
4239 DeclContext::lookup_const_iterator Con, ConEnd;
4240 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4241 Con != ConEnd; ++Con) {
4242 // FIXME: In C++0x, a constructor template can be a default constructor.
4243 if (isa<FunctionTemplateDecl>(*Con))
4244 continue;
4245
4246 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4247 if (Constructor->isDefaultConstructor())
4248 return Constructor;
4249 }
4250 return 0;
4251}
4252
Douglas Gregor0be31a22010-07-02 17:43:08 +00004253CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4254 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004255 // C++ [class.ctor]p5:
4256 // A default constructor for a class X is a constructor of class X
4257 // that can be called without an argument. If there is no
4258 // user-declared constructor for class X, a default constructor is
4259 // implicitly declared. An implicitly-declared default constructor
4260 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004261 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4262 "Should not build implicit default constructor!");
4263
Douglas Gregor6d880b12010-07-01 22:31:05 +00004264 // C++ [except.spec]p14:
4265 // An implicitly declared special member function (Clause 12) shall have an
4266 // exception-specification. [...]
4267 ImplicitExceptionSpecification ExceptSpec(Context);
4268
4269 // Direct base-class destructors.
4270 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4271 BEnd = ClassDecl->bases_end();
4272 B != BEnd; ++B) {
4273 if (B->isVirtual()) // Handled below.
4274 continue;
4275
Douglas Gregor9672f922010-07-03 00:47:00 +00004276 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4277 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4278 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4279 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004280 else if (CXXConstructorDecl *Constructor
4281 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004282 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004283 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004284 }
4285
4286 // Virtual base-class destructors.
4287 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4288 BEnd = ClassDecl->vbases_end();
4289 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004290 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4291 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4292 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4293 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4294 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004295 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004296 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004297 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004298 }
4299
4300 // Field destructors.
4301 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4302 FEnd = ClassDecl->field_end();
4303 F != FEnd; ++F) {
4304 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004305 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4306 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4307 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4308 ExceptSpec.CalledDecl(
4309 DeclareImplicitDefaultConstructor(FieldClassDecl));
4310 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004311 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004312 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004313 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004314 }
4315
4316
4317 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004318 CanQualType ClassType
4319 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4320 DeclarationName Name
4321 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004322 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004323 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004324 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004325 Context.getFunctionType(Context.VoidTy,
4326 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004327 ExceptSpec.hasExceptionSpecification(),
4328 ExceptSpec.hasAnyExceptionSpecification(),
4329 ExceptSpec.size(),
4330 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004331 FunctionType::ExtInfo()),
4332 /*TInfo=*/0,
4333 /*isExplicit=*/false,
4334 /*isInline=*/true,
4335 /*isImplicitlyDeclared=*/true);
4336 DefaultCon->setAccess(AS_public);
4337 DefaultCon->setImplicit();
4338 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004339
4340 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004341 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4342
Douglas Gregor0be31a22010-07-02 17:43:08 +00004343 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004344 PushOnScopeChains(DefaultCon, S, false);
4345 ClassDecl->addDecl(DefaultCon);
4346
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004347 return DefaultCon;
4348}
4349
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004350void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4351 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004352 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004353 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004354 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004355
Anders Carlsson423f5d82010-04-23 16:04:08 +00004356 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004357 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004358
Douglas Gregora57478e2010-05-01 15:04:51 +00004359 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004360 ErrorTrap Trap(*this);
4361 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4362 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004363 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004364 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004365 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004366 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004367 }
Douglas Gregor73193272010-09-20 16:48:21 +00004368
4369 SourceLocation Loc = Constructor->getLocation();
4370 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4371
4372 Constructor->setUsed();
4373 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004374}
4375
Douglas Gregor0be31a22010-07-02 17:43:08 +00004376CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004377 // C++ [class.dtor]p2:
4378 // If a class has no user-declared destructor, a destructor is
4379 // declared implicitly. An implicitly-declared destructor is an
4380 // inline public member of its class.
4381
4382 // C++ [except.spec]p14:
4383 // An implicitly declared special member function (Clause 12) shall have
4384 // an exception-specification.
4385 ImplicitExceptionSpecification ExceptSpec(Context);
4386
4387 // Direct base-class destructors.
4388 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4389 BEnd = ClassDecl->bases_end();
4390 B != BEnd; ++B) {
4391 if (B->isVirtual()) // Handled below.
4392 continue;
4393
4394 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4395 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004396 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004397 }
4398
4399 // Virtual base-class destructors.
4400 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4401 BEnd = ClassDecl->vbases_end();
4402 B != BEnd; ++B) {
4403 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4404 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004405 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004406 }
4407
4408 // Field destructors.
4409 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4410 FEnd = ClassDecl->field_end();
4411 F != FEnd; ++F) {
4412 if (const RecordType *RecordTy
4413 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4414 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004415 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004416 }
4417
Douglas Gregor7454c562010-07-02 20:37:36 +00004418 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004419 QualType Ty = Context.getFunctionType(Context.VoidTy,
4420 0, 0, false, 0,
4421 ExceptSpec.hasExceptionSpecification(),
4422 ExceptSpec.hasAnyExceptionSpecification(),
4423 ExceptSpec.size(),
4424 ExceptSpec.data(),
4425 FunctionType::ExtInfo());
4426
4427 CanQualType ClassType
4428 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4429 DeclarationName Name
4430 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004431 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004432 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004433 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004434 /*isInline=*/true,
4435 /*isImplicitlyDeclared=*/true);
4436 Destructor->setAccess(AS_public);
4437 Destructor->setImplicit();
4438 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004439
4440 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004441 ++ASTContext::NumImplicitDestructorsDeclared;
4442
4443 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004444 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004445 PushOnScopeChains(Destructor, S, false);
4446 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004447
4448 // This could be uniqued if it ever proves significant.
4449 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4450
4451 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004452
Douglas Gregorf1203042010-07-01 19:09:28 +00004453 return Destructor;
4454}
4455
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004456void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004457 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004458 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004459 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004460 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004461 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004462
Douglas Gregor54818f02010-05-12 16:39:35 +00004463 if (Destructor->isInvalidDecl())
4464 return;
4465
Douglas Gregora57478e2010-05-01 15:04:51 +00004466 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004467
Douglas Gregor54818f02010-05-12 16:39:35 +00004468 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004469 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4470 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregor54818f02010-05-12 16:39:35 +00004472 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004473 Diag(CurrentLocation, diag::note_member_synthesized_at)
4474 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4475
4476 Destructor->setInvalidDecl();
4477 return;
4478 }
4479
Douglas Gregor73193272010-09-20 16:48:21 +00004480 SourceLocation Loc = Destructor->getLocation();
4481 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4482
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004483 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004484 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004485}
4486
Douglas Gregorb139cd52010-05-01 20:49:11 +00004487/// \brief Builds a statement that copies the given entity from \p From to
4488/// \c To.
4489///
4490/// This routine is used to copy the members of a class with an
4491/// implicitly-declared copy assignment operator. When the entities being
4492/// copied are arrays, this routine builds for loops to copy them.
4493///
4494/// \param S The Sema object used for type-checking.
4495///
4496/// \param Loc The location where the implicit copy is being generated.
4497///
4498/// \param T The type of the expressions being copied. Both expressions must
4499/// have this type.
4500///
4501/// \param To The expression we are copying to.
4502///
4503/// \param From The expression we are copying from.
4504///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004505/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4506/// Otherwise, it's a non-static member subobject.
4507///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004508/// \param Depth Internal parameter recording the depth of the recursion.
4509///
4510/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004511static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004512BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004513 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004514 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004515 // C++0x [class.copy]p30:
4516 // Each subobject is assigned in the manner appropriate to its type:
4517 //
4518 // - if the subobject is of class type, the copy assignment operator
4519 // for the class is used (as if by explicit qualification; that is,
4520 // ignoring any possible virtual overriding functions in more derived
4521 // classes);
4522 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4523 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4524
4525 // Look for operator=.
4526 DeclarationName Name
4527 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4528 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4529 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4530
4531 // Filter out any result that isn't a copy-assignment operator.
4532 LookupResult::Filter F = OpLookup.makeFilter();
4533 while (F.hasNext()) {
4534 NamedDecl *D = F.next();
4535 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4536 if (Method->isCopyAssignmentOperator())
4537 continue;
4538
4539 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004540 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004541 F.done();
4542
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004543 // Suppress the protected check (C++ [class.protected]) for each of the
4544 // assignment operators we found. This strange dance is required when
4545 // we're assigning via a base classes's copy-assignment operator. To
4546 // ensure that we're getting the right base class subobject (without
4547 // ambiguities), we need to cast "this" to that subobject type; to
4548 // ensure that we don't go through the virtual call mechanism, we need
4549 // to qualify the operator= name with the base class (see below). However,
4550 // this means that if the base class has a protected copy assignment
4551 // operator, the protected member access check will fail. So, we
4552 // rewrite "protected" access to "public" access in this case, since we
4553 // know by construction that we're calling from a derived class.
4554 if (CopyingBaseSubobject) {
4555 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4556 L != LEnd; ++L) {
4557 if (L.getAccess() == AS_protected)
4558 L.setAccess(AS_public);
4559 }
4560 }
4561
Douglas Gregorb139cd52010-05-01 20:49:11 +00004562 // Create the nested-name-specifier that will be used to qualify the
4563 // reference to operator=; this is required to suppress the virtual
4564 // call mechanism.
4565 CXXScopeSpec SS;
4566 SS.setRange(Loc);
4567 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4568 T.getTypePtr()));
4569
4570 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004571 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004572 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004573 /*FirstQualifierInScope=*/0, OpLookup,
4574 /*TemplateArgs=*/0,
4575 /*SuppressQualifierCheck=*/true);
4576 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004577 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004578
4579 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004580
John McCalldadc5752010-08-24 06:29:42 +00004581 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004582 OpEqualRef.takeAs<Expr>(),
4583 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004584 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004585 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004586
4587 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004588 }
John McCallab8c2732010-03-16 06:11:48 +00004589
Douglas Gregorb139cd52010-05-01 20:49:11 +00004590 // - if the subobject is of scalar type, the built-in assignment
4591 // operator is used.
4592 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4593 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004594 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004595 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004596 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004597
4598 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004599 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004600
4601 // - if the subobject is an array, each element is assigned, in the
4602 // manner appropriate to the element type;
4603
4604 // Construct a loop over the array bounds, e.g.,
4605 //
4606 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4607 //
4608 // that will copy each of the array elements.
4609 QualType SizeType = S.Context.getSizeType();
4610
4611 // Create the iteration variable.
4612 IdentifierInfo *IterationVarName = 0;
4613 {
4614 llvm::SmallString<8> Str;
4615 llvm::raw_svector_ostream OS(Str);
4616 OS << "__i" << Depth;
4617 IterationVarName = &S.Context.Idents.get(OS.str());
4618 }
4619 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4620 IterationVarName, SizeType,
4621 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004622 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004623
4624 // Initialize the iteration variable to zero.
4625 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004626 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004627
4628 // Create a reference to the iteration variable; we'll use this several
4629 // times throughout.
4630 Expr *IterationVarRef
4631 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4632 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4633
4634 // Create the DeclStmt that holds the iteration variable.
4635 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4636
4637 // Create the comparison against the array bound.
4638 llvm::APInt Upper = ArrayTy->getSize();
4639 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004640 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004641 = new (S.Context) BinaryOperator(IterationVarRef,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004642 IntegerLiteral::Create(S.Context,
4643 Upper, SizeType, Loc),
4644 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004645
4646 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004647 Expr *Increment
John McCallc3007a22010-10-26 07:05:15 +00004648 = new (S.Context) UnaryOperator(IterationVarRef,
John McCalle3027922010-08-25 11:45:40 +00004649 UO_PreInc,
John McCallb268a282010-08-23 23:25:46 +00004650 SizeType, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004651
4652 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004653 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4654 IterationVarRef, Loc));
4655 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4656 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004657
4658 // Build the copy for an individual element of the array.
John McCalldadc5752010-08-24 06:29:42 +00004659 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004660 ArrayTy->getElementType(),
John McCallb268a282010-08-23 23:25:46 +00004661 To, From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004662 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004663 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004664 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004665
4666 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004667 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004668 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004669 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004670 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004671}
4672
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004673/// \brief Determine whether the given class has a copy assignment operator
4674/// that accepts a const-qualified argument.
4675static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4676 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4677
4678 if (!Class->hasDeclaredCopyAssignment())
4679 S.DeclareImplicitCopyAssignment(Class);
4680
4681 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4682 DeclarationName OpName
4683 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4684
4685 DeclContext::lookup_const_iterator Op, OpEnd;
4686 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4687 // C++ [class.copy]p9:
4688 // A user-declared copy assignment operator is a non-static non-template
4689 // member function of class X with exactly one parameter of type X, X&,
4690 // const X&, volatile X& or const volatile X&.
4691 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4692 if (!Method)
4693 continue;
4694
4695 if (Method->isStatic())
4696 continue;
4697 if (Method->getPrimaryTemplate())
4698 continue;
4699 const FunctionProtoType *FnType =
4700 Method->getType()->getAs<FunctionProtoType>();
4701 assert(FnType && "Overloaded operator has no prototype.");
4702 // Don't assert on this; an invalid decl might have been left in the AST.
4703 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4704 continue;
4705 bool AcceptsConst = true;
4706 QualType ArgType = FnType->getArgType(0);
4707 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4708 ArgType = Ref->getPointeeType();
4709 // Is it a non-const lvalue reference?
4710 if (!ArgType.isConstQualified())
4711 AcceptsConst = false;
4712 }
4713 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4714 continue;
4715
4716 // We have a single argument of type cv X or cv X&, i.e. we've found the
4717 // copy assignment operator. Return whether it accepts const arguments.
4718 return AcceptsConst;
4719 }
4720 assert(Class->isInvalidDecl() &&
4721 "No copy assignment operator declared in valid code.");
4722 return false;
4723}
4724
Douglas Gregor0be31a22010-07-02 17:43:08 +00004725CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004726 // Note: The following rules are largely analoguous to the copy
4727 // constructor rules. Note that virtual bases are not taken into account
4728 // for determining the argument type of the operator. Note also that
4729 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004730
4731
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004732 // C++ [class.copy]p10:
4733 // If the class definition does not explicitly declare a copy
4734 // assignment operator, one is declared implicitly.
4735 // The implicitly-defined copy assignment operator for a class X
4736 // will have the form
4737 //
4738 // X& X::operator=(const X&)
4739 //
4740 // if
4741 bool HasConstCopyAssignment = true;
4742
4743 // -- each direct base class B of X has a copy assignment operator
4744 // whose parameter is of type const B&, const volatile B& or B,
4745 // and
4746 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4747 BaseEnd = ClassDecl->bases_end();
4748 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4749 assert(!Base->getType()->isDependentType() &&
4750 "Cannot generate implicit members for class with dependent bases.");
4751 const CXXRecordDecl *BaseClassDecl
4752 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004753 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004754 }
4755
4756 // -- for all the nonstatic data members of X that are of a class
4757 // type M (or array thereof), each such class type has a copy
4758 // assignment operator whose parameter is of type const M&,
4759 // const volatile M& or M.
4760 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4761 FieldEnd = ClassDecl->field_end();
4762 HasConstCopyAssignment && Field != FieldEnd;
4763 ++Field) {
4764 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4765 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4766 const CXXRecordDecl *FieldClassDecl
4767 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004768 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004769 }
4770 }
4771
4772 // Otherwise, the implicitly declared copy assignment operator will
4773 // have the form
4774 //
4775 // X& X::operator=(X&)
4776 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4777 QualType RetType = Context.getLValueReferenceType(ArgType);
4778 if (HasConstCopyAssignment)
4779 ArgType = ArgType.withConst();
4780 ArgType = Context.getLValueReferenceType(ArgType);
4781
Douglas Gregor68e11362010-07-01 17:48:08 +00004782 // C++ [except.spec]p14:
4783 // An implicitly declared special member function (Clause 12) shall have an
4784 // exception-specification. [...]
4785 ImplicitExceptionSpecification ExceptSpec(Context);
4786 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4787 BaseEnd = ClassDecl->bases_end();
4788 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004789 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004790 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004791
4792 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4793 DeclareImplicitCopyAssignment(BaseClassDecl);
4794
Douglas Gregor68e11362010-07-01 17:48:08 +00004795 if (CXXMethodDecl *CopyAssign
4796 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4797 ExceptSpec.CalledDecl(CopyAssign);
4798 }
4799 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4800 FieldEnd = ClassDecl->field_end();
4801 Field != FieldEnd;
4802 ++Field) {
4803 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4804 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004805 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004806 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004807
4808 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4809 DeclareImplicitCopyAssignment(FieldClassDecl);
4810
Douglas Gregor68e11362010-07-01 17:48:08 +00004811 if (CXXMethodDecl *CopyAssign
4812 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4813 ExceptSpec.CalledDecl(CopyAssign);
4814 }
4815 }
4816
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004817 // An implicitly-declared copy assignment operator is an inline public
4818 // member of its class.
4819 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004820 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004821 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004822 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004823 Context.getFunctionType(RetType, &ArgType, 1,
4824 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004825 ExceptSpec.hasExceptionSpecification(),
4826 ExceptSpec.hasAnyExceptionSpecification(),
4827 ExceptSpec.size(),
4828 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004829 FunctionType::ExtInfo()),
4830 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004831 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004832 /*isInline=*/true);
4833 CopyAssignment->setAccess(AS_public);
4834 CopyAssignment->setImplicit();
4835 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004836
4837 // Add the parameter to the operator.
4838 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4839 ClassDecl->getLocation(),
4840 /*Id=*/0,
4841 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004842 SC_None,
4843 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004844 CopyAssignment->setParams(&FromParam, 1);
4845
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004846 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004847 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4848
Douglas Gregor0be31a22010-07-02 17:43:08 +00004849 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004850 PushOnScopeChains(CopyAssignment, S, false);
4851 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004852
4853 AddOverriddenMethods(ClassDecl, CopyAssignment);
4854 return CopyAssignment;
4855}
4856
Douglas Gregorb139cd52010-05-01 20:49:11 +00004857void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4858 CXXMethodDecl *CopyAssignOperator) {
4859 assert((CopyAssignOperator->isImplicit() &&
4860 CopyAssignOperator->isOverloadedOperator() &&
4861 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004862 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004863 "DefineImplicitCopyAssignment called for wrong function");
4864
4865 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4866
4867 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4868 CopyAssignOperator->setInvalidDecl();
4869 return;
4870 }
4871
4872 CopyAssignOperator->setUsed();
4873
4874 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004875 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004876
4877 // C++0x [class.copy]p30:
4878 // The implicitly-defined or explicitly-defaulted copy assignment operator
4879 // for a non-union class X performs memberwise copy assignment of its
4880 // subobjects. The direct base classes of X are assigned first, in the
4881 // order of their declaration in the base-specifier-list, and then the
4882 // immediate non-static data members of X are assigned, in the order in
4883 // which they were declared in the class definition.
4884
4885 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004886 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004887
4888 // The parameter for the "other" object, which we are copying from.
4889 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4890 Qualifiers OtherQuals = Other->getType().getQualifiers();
4891 QualType OtherRefType = Other->getType();
4892 if (const LValueReferenceType *OtherRef
4893 = OtherRefType->getAs<LValueReferenceType>()) {
4894 OtherRefType = OtherRef->getPointeeType();
4895 OtherQuals = OtherRefType.getQualifiers();
4896 }
4897
4898 // Our location for everything implicitly-generated.
4899 SourceLocation Loc = CopyAssignOperator->getLocation();
4900
4901 // Construct a reference to the "other" object. We'll be using this
4902 // throughout the generated ASTs.
4903 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4904 assert(OtherRef && "Reference to parameter cannot fail!");
4905
4906 // Construct the "this" pointer. We'll be using this throughout the generated
4907 // ASTs.
4908 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4909 assert(This && "Reference to this cannot fail!");
4910
4911 // Assign base classes.
4912 bool Invalid = false;
4913 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4914 E = ClassDecl->bases_end(); Base != E; ++Base) {
4915 // Form the assignment:
4916 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4917 QualType BaseType = Base->getType().getUnqualifiedType();
4918 CXXRecordDecl *BaseClassDecl = 0;
4919 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4920 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4921 else {
4922 Invalid = true;
4923 continue;
4924 }
4925
John McCallcf142162010-08-07 06:22:56 +00004926 CXXCastPath BasePath;
4927 BasePath.push_back(Base);
4928
Douglas Gregorb139cd52010-05-01 20:49:11 +00004929 // Construct the "from" expression, which is an implicit cast to the
4930 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00004931 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004932 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004933 CK_UncheckedDerivedToBase,
4934 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004935
4936 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004937 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004938
4939 // Implicitly cast "this" to the appropriately-qualified base type.
4940 Expr *ToE = To.takeAs<Expr>();
4941 ImpCastExprToType(ToE,
4942 Context.getCVRQualifiedType(BaseType,
4943 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004944 CK_UncheckedDerivedToBase,
4945 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004946 To = Owned(ToE);
4947
4948 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004949 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004950 To.get(), From,
4951 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004952 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004953 Diag(CurrentLocation, diag::note_member_synthesized_at)
4954 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4955 CopyAssignOperator->setInvalidDecl();
4956 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004957 }
4958
4959 // Success! Record the copy.
4960 Statements.push_back(Copy.takeAs<Expr>());
4961 }
4962
4963 // \brief Reference to the __builtin_memcpy function.
4964 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004965 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004966 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004967
4968 // Assign non-static members.
4969 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4970 FieldEnd = ClassDecl->field_end();
4971 Field != FieldEnd; ++Field) {
4972 // Check for members of reference type; we can't copy those.
4973 if (Field->getType()->isReferenceType()) {
4974 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4975 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4976 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004977 Diag(CurrentLocation, diag::note_member_synthesized_at)
4978 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004979 Invalid = true;
4980 continue;
4981 }
4982
4983 // Check for members of const-qualified, non-class type.
4984 QualType BaseType = Context.getBaseElementType(Field->getType());
4985 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4986 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4987 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4988 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004989 Diag(CurrentLocation, diag::note_member_synthesized_at)
4990 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004991 Invalid = true;
4992 continue;
4993 }
4994
4995 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004996 if (FieldType->isIncompleteArrayType()) {
4997 assert(ClassDecl->hasFlexibleArrayMember() &&
4998 "Incomplete array type is not valid");
4999 continue;
5000 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005001
5002 // Build references to the field in the object we're copying from and to.
5003 CXXScopeSpec SS; // Intentionally empty
5004 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5005 LookupMemberName);
5006 MemberLookup.addDecl(*Field);
5007 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005008 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005009 Loc, /*IsArrow=*/false,
5010 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005011 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005012 Loc, /*IsArrow=*/true,
5013 SS, 0, MemberLookup, 0);
5014 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5015 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5016
5017 // If the field should be copied with __builtin_memcpy rather than via
5018 // explicit assignments, do so. This optimization only applies for arrays
5019 // of scalars and arrays of class type with trivial copy-assignment
5020 // operators.
5021 if (FieldType->isArrayType() &&
5022 (!BaseType->isRecordType() ||
5023 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5024 ->hasTrivialCopyAssignment())) {
5025 // Compute the size of the memory buffer to be copied.
5026 QualType SizeType = Context.getSizeType();
5027 llvm::APInt Size(Context.getTypeSize(SizeType),
5028 Context.getTypeSizeInChars(BaseType).getQuantity());
5029 for (const ConstantArrayType *Array
5030 = Context.getAsConstantArrayType(FieldType);
5031 Array;
5032 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5033 llvm::APInt ArraySize = Array->getSize();
5034 ArraySize.zextOrTrunc(Size.getBitWidth());
5035 Size *= ArraySize;
5036 }
5037
5038 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005039 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5040 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005041
5042 bool NeedsCollectableMemCpy =
5043 (BaseType->isRecordType() &&
5044 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5045
5046 if (NeedsCollectableMemCpy) {
5047 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005048 // Create a reference to the __builtin_objc_memmove_collectable function.
5049 LookupResult R(*this,
5050 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005051 Loc, LookupOrdinaryName);
5052 LookupName(R, TUScope, true);
5053
5054 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5055 if (!CollectableMemCpy) {
5056 // Something went horribly wrong earlier, and we will have
5057 // complained about it.
5058 Invalid = true;
5059 continue;
5060 }
5061
5062 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5063 CollectableMemCpy->getType(),
5064 Loc, 0).takeAs<Expr>();
5065 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5066 }
5067 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005068 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005069 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005070 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5071 LookupOrdinaryName);
5072 LookupName(R, TUScope, true);
5073
5074 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5075 if (!BuiltinMemCpy) {
5076 // Something went horribly wrong earlier, and we will have complained
5077 // about it.
5078 Invalid = true;
5079 continue;
5080 }
5081
5082 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5083 BuiltinMemCpy->getType(),
5084 Loc, 0).takeAs<Expr>();
5085 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5086 }
5087
John McCall37ad5512010-08-23 06:44:23 +00005088 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005089 CallArgs.push_back(To.takeAs<Expr>());
5090 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005091 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005092 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005093 if (NeedsCollectableMemCpy)
5094 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005095 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005096 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005097 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005098 else
5099 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005100 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005101 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005102 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005103
Douglas Gregorb139cd52010-05-01 20:49:11 +00005104 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5105 Statements.push_back(Call.takeAs<Expr>());
5106 continue;
5107 }
5108
5109 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005110 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005111 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005112 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005113 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005114 Diag(CurrentLocation, diag::note_member_synthesized_at)
5115 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5116 CopyAssignOperator->setInvalidDecl();
5117 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005118 }
5119
5120 // Success! Record the copy.
5121 Statements.push_back(Copy.takeAs<Stmt>());
5122 }
5123
5124 if (!Invalid) {
5125 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005126 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005127
John McCalldadc5752010-08-24 06:29:42 +00005128 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005129 if (Return.isInvalid())
5130 Invalid = true;
5131 else {
5132 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005133
5134 if (Trap.hasErrorOccurred()) {
5135 Diag(CurrentLocation, diag::note_member_synthesized_at)
5136 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5137 Invalid = true;
5138 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005139 }
5140 }
5141
5142 if (Invalid) {
5143 CopyAssignOperator->setInvalidDecl();
5144 return;
5145 }
5146
John McCalldadc5752010-08-24 06:29:42 +00005147 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005148 /*isStmtExpr=*/false);
5149 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5150 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005151}
5152
Douglas Gregor0be31a22010-07-02 17:43:08 +00005153CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5154 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005155 // C++ [class.copy]p4:
5156 // If the class definition does not explicitly declare a copy
5157 // constructor, one is declared implicitly.
5158
Douglas Gregor54be3392010-07-01 17:57:27 +00005159 // C++ [class.copy]p5:
5160 // The implicitly-declared copy constructor for a class X will
5161 // have the form
5162 //
5163 // X::X(const X&)
5164 //
5165 // if
5166 bool HasConstCopyConstructor = true;
5167
5168 // -- each direct or virtual base class B of X has a copy
5169 // constructor whose first parameter is of type const B& or
5170 // const volatile B&, and
5171 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5172 BaseEnd = ClassDecl->bases_end();
5173 HasConstCopyConstructor && Base != BaseEnd;
5174 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005175 // Virtual bases are handled below.
5176 if (Base->isVirtual())
5177 continue;
5178
Douglas Gregora6d69502010-07-02 23:41:54 +00005179 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005180 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005181 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5182 DeclareImplicitCopyConstructor(BaseClassDecl);
5183
Douglas Gregorcfe68222010-07-01 18:27:03 +00005184 HasConstCopyConstructor
5185 = BaseClassDecl->hasConstCopyConstructor(Context);
5186 }
5187
5188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5189 BaseEnd = ClassDecl->vbases_end();
5190 HasConstCopyConstructor && Base != BaseEnd;
5191 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005192 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005193 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005194 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5195 DeclareImplicitCopyConstructor(BaseClassDecl);
5196
Douglas Gregor54be3392010-07-01 17:57:27 +00005197 HasConstCopyConstructor
5198 = BaseClassDecl->hasConstCopyConstructor(Context);
5199 }
5200
5201 // -- for all the nonstatic data members of X that are of a
5202 // class type M (or array thereof), each such class type
5203 // has a copy constructor whose first parameter is of type
5204 // const M& or const volatile M&.
5205 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5206 FieldEnd = ClassDecl->field_end();
5207 HasConstCopyConstructor && Field != FieldEnd;
5208 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005209 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005210 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005211 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005212 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005213 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5214 DeclareImplicitCopyConstructor(FieldClassDecl);
5215
Douglas Gregor54be3392010-07-01 17:57:27 +00005216 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005217 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005218 }
5219 }
5220
5221 // Otherwise, the implicitly declared copy constructor will have
5222 // the form
5223 //
5224 // X::X(X&)
5225 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5226 QualType ArgType = ClassType;
5227 if (HasConstCopyConstructor)
5228 ArgType = ArgType.withConst();
5229 ArgType = Context.getLValueReferenceType(ArgType);
5230
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005231 // C++ [except.spec]p14:
5232 // An implicitly declared special member function (Clause 12) shall have an
5233 // exception-specification. [...]
5234 ImplicitExceptionSpecification ExceptSpec(Context);
5235 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5236 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5237 BaseEnd = ClassDecl->bases_end();
5238 Base != BaseEnd;
5239 ++Base) {
5240 // Virtual bases are handled below.
5241 if (Base->isVirtual())
5242 continue;
5243
Douglas Gregora6d69502010-07-02 23:41:54 +00005244 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005245 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005246 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5247 DeclareImplicitCopyConstructor(BaseClassDecl);
5248
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005249 if (CXXConstructorDecl *CopyConstructor
5250 = BaseClassDecl->getCopyConstructor(Context, Quals))
5251 ExceptSpec.CalledDecl(CopyConstructor);
5252 }
5253 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5254 BaseEnd = ClassDecl->vbases_end();
5255 Base != BaseEnd;
5256 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005257 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005258 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005259 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5260 DeclareImplicitCopyConstructor(BaseClassDecl);
5261
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005262 if (CXXConstructorDecl *CopyConstructor
5263 = BaseClassDecl->getCopyConstructor(Context, Quals))
5264 ExceptSpec.CalledDecl(CopyConstructor);
5265 }
5266 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5267 FieldEnd = ClassDecl->field_end();
5268 Field != FieldEnd;
5269 ++Field) {
5270 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5271 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005272 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005273 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005274 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5275 DeclareImplicitCopyConstructor(FieldClassDecl);
5276
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005277 if (CXXConstructorDecl *CopyConstructor
5278 = FieldClassDecl->getCopyConstructor(Context, Quals))
5279 ExceptSpec.CalledDecl(CopyConstructor);
5280 }
5281 }
5282
Douglas Gregor54be3392010-07-01 17:57:27 +00005283 // An implicitly-declared copy constructor is an inline public
5284 // member of its class.
5285 DeclarationName Name
5286 = Context.DeclarationNames.getCXXConstructorName(
5287 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005288 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005289 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005290 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005291 Context.getFunctionType(Context.VoidTy,
5292 &ArgType, 1,
5293 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005294 ExceptSpec.hasExceptionSpecification(),
5295 ExceptSpec.hasAnyExceptionSpecification(),
5296 ExceptSpec.size(),
5297 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005298 FunctionType::ExtInfo()),
5299 /*TInfo=*/0,
5300 /*isExplicit=*/false,
5301 /*isInline=*/true,
5302 /*isImplicitlyDeclared=*/true);
5303 CopyConstructor->setAccess(AS_public);
5304 CopyConstructor->setImplicit();
5305 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5306
Douglas Gregora6d69502010-07-02 23:41:54 +00005307 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005308 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5309
Douglas Gregor54be3392010-07-01 17:57:27 +00005310 // Add the parameter to the constructor.
5311 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5312 ClassDecl->getLocation(),
5313 /*IdentifierInfo=*/0,
5314 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005315 SC_None,
5316 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005317 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005318 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005319 PushOnScopeChains(CopyConstructor, S, false);
5320 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005321
5322 return CopyConstructor;
5323}
5324
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005325void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5326 CXXConstructorDecl *CopyConstructor,
5327 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005328 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005329 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005330 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005331 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005332
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005333 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005334 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005335
Douglas Gregora57478e2010-05-01 15:04:51 +00005336 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005337 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005338
Douglas Gregor54818f02010-05-12 16:39:35 +00005339 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5340 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005341 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005342 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005343 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005344 } else {
5345 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5346 CopyConstructor->getLocation(),
5347 MultiStmtArg(*this, 0, 0),
5348 /*isStmtExpr=*/false)
5349 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005350 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005351
5352 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005353}
5354
John McCalldadc5752010-08-24 06:29:42 +00005355ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005356Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005357 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005358 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005359 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005360 unsigned ConstructKind,
5361 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005362 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005363
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005364 // C++0x [class.copy]p34:
5365 // When certain criteria are met, an implementation is allowed to
5366 // omit the copy/move construction of a class object, even if the
5367 // copy/move constructor and/or destructor for the object have
5368 // side effects. [...]
5369 // - when a temporary class object that has not been bound to a
5370 // reference (12.2) would be copied/moved to a class object
5371 // with the same cv-unqualified type, the copy/move operation
5372 // can be omitted by constructing the temporary object
5373 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005374 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5375 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005376 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005377 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005378 }
Mike Stump11289f42009-09-09 15:08:12 +00005379
5380 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005381 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005382 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005383}
5384
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005385/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5386/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005387ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005388Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5389 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005390 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005391 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005392 unsigned ConstructKind,
5393 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005394 unsigned NumExprs = ExprArgs.size();
5395 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005396
Douglas Gregor27381f32009-11-23 12:27:39 +00005397 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005398 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005399 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005400 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005401 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5402 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005403}
5404
Mike Stump11289f42009-09-09 15:08:12 +00005405bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005406 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005407 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005408 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005409 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005410 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005411 move(Exprs), false, CXXConstructExpr::CK_Complete,
5412 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005413 if (TempResult.isInvalid())
5414 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005415
Anders Carlsson6eb55572009-08-25 05:12:04 +00005416 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005417 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005418 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005419 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005420 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005421
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005422 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005423}
5424
John McCall03c48482010-02-02 09:10:11 +00005425void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5426 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005427 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005428 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005429 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005430 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005431 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005432 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005433 << VD->getDeclName()
5434 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005435
John McCall386dfc72010-09-18 05:25:11 +00005436 // TODO: this should be re-enabled for static locals by !CXAAtExit
5437 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005438 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005439 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005440}
5441
Mike Stump11289f42009-09-09 15:08:12 +00005442/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005443/// ActOnDeclarator, when a C++ direct initializer is present.
5444/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005445void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005446 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005447 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005448 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005449 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005450
5451 // If there is no declaration, there was an error parsing it. Just ignore
5452 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005453 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005454 return;
Mike Stump11289f42009-09-09 15:08:12 +00005455
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005456 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5457 if (!VDecl) {
5458 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5459 RealDecl->setInvalidDecl();
5460 return;
5461 }
5462
Douglas Gregor402250f2009-08-26 21:14:46 +00005463 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005464 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005465 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5466 //
5467 // Clients that want to distinguish between the two forms, can check for
5468 // direct initializer using VarDecl::hasCXXDirectInitializer().
5469 // A major benefit is that clients that don't particularly care about which
5470 // exactly form was it (like the CodeGen) can handle both cases without
5471 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005472
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005473 // C++ 8.5p11:
5474 // The form of initialization (using parentheses or '=') is generally
5475 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005476 // class type.
5477
Douglas Gregor50dc2192010-02-11 22:55:30 +00005478 if (!VDecl->getType()->isDependentType() &&
5479 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005480 diag::err_typecheck_decl_incomplete_type)) {
5481 VDecl->setInvalidDecl();
5482 return;
5483 }
5484
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005485 // The variable can not have an abstract class type.
5486 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5487 diag::err_abstract_type_in_decl,
5488 AbstractVariableType))
5489 VDecl->setInvalidDecl();
5490
Sebastian Redl5ca79842010-02-01 20:16:42 +00005491 const VarDecl *Def;
5492 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005493 Diag(VDecl->getLocation(), diag::err_redefinition)
5494 << VDecl->getDeclName();
5495 Diag(Def->getLocation(), diag::note_previous_definition);
5496 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005497 return;
5498 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005499
Douglas Gregorf0f83692010-08-24 05:27:49 +00005500 // C++ [class.static.data]p4
5501 // If a static data member is of const integral or const
5502 // enumeration type, its declaration in the class definition can
5503 // specify a constant-initializer which shall be an integral
5504 // constant expression (5.19). In that case, the member can appear
5505 // in integral constant expressions. The member shall still be
5506 // defined in a namespace scope if it is used in the program and the
5507 // namespace scope definition shall not contain an initializer.
5508 //
5509 // We already performed a redefinition check above, but for static
5510 // data members we also need to check whether there was an in-class
5511 // declaration with an initializer.
5512 const VarDecl* PrevInit = 0;
5513 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5514 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5515 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5516 return;
5517 }
5518
Douglas Gregor50dc2192010-02-11 22:55:30 +00005519 // If either the declaration has a dependent type or if any of the
5520 // expressions is type-dependent, we represent the initialization
5521 // via a ParenListExpr for later use during template instantiation.
5522 if (VDecl->getType()->isDependentType() ||
5523 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5524 // Let clients know that initialization was done with a direct initializer.
5525 VDecl->setCXXDirectInitializer(true);
5526
5527 // Store the initialization expressions as a ParenListExpr.
5528 unsigned NumExprs = Exprs.size();
5529 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5530 (Expr **)Exprs.release(),
5531 NumExprs, RParenLoc));
5532 return;
5533 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005534
5535 // Capture the variable that is being initialized and the style of
5536 // initialization.
5537 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5538
5539 // FIXME: Poor source location information.
5540 InitializationKind Kind
5541 = InitializationKind::CreateDirect(VDecl->getLocation(),
5542 LParenLoc, RParenLoc);
5543
5544 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005545 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005546 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005547 if (Result.isInvalid()) {
5548 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005549 return;
5550 }
John McCallacf0ee52010-10-08 02:01:28 +00005551
5552 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005553
John McCallb268a282010-08-23 23:25:46 +00005554 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregord5058122010-02-11 01:19:42 +00005555 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005556 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005557
John McCall8b0f4ff2010-08-02 21:13:48 +00005558 if (!VDecl->isInvalidDecl() &&
5559 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005560 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005561 !VDecl->getInit()->isConstantInitializer(Context,
5562 VDecl->getType()->isReferenceType()))
5563 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5564 << VDecl->getInit()->getSourceRange();
5565
John McCall03c48482010-02-02 09:10:11 +00005566 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5567 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005568}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005569
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005570/// \brief Given a constructor and the set of arguments provided for the
5571/// constructor, convert the arguments and add any required default arguments
5572/// to form a proper call to this constructor.
5573///
5574/// \returns true if an error occurred, false otherwise.
5575bool
5576Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5577 MultiExprArg ArgsPtr,
5578 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005579 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005580 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5581 unsigned NumArgs = ArgsPtr.size();
5582 Expr **Args = (Expr **)ArgsPtr.get();
5583
5584 const FunctionProtoType *Proto
5585 = Constructor->getType()->getAs<FunctionProtoType>();
5586 assert(Proto && "Constructor without a prototype?");
5587 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005588
5589 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005590 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005591 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005592 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005593 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005594
5595 VariadicCallType CallType =
5596 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5597 llvm::SmallVector<Expr *, 8> AllArgs;
5598 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5599 Proto, 0, Args, NumArgs, AllArgs,
5600 CallType);
5601 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5602 ConvertedArgs.push_back(AllArgs[i]);
5603 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005604}
5605
Anders Carlssone363c8e2009-12-12 00:32:00 +00005606static inline bool
5607CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5608 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005609 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005610 if (isa<NamespaceDecl>(DC)) {
5611 return SemaRef.Diag(FnDecl->getLocation(),
5612 diag::err_operator_new_delete_declared_in_namespace)
5613 << FnDecl->getDeclName();
5614 }
5615
5616 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005617 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005618 return SemaRef.Diag(FnDecl->getLocation(),
5619 diag::err_operator_new_delete_declared_static)
5620 << FnDecl->getDeclName();
5621 }
5622
Anders Carlsson60659a82009-12-12 02:43:16 +00005623 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005624}
5625
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005626static inline bool
5627CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5628 CanQualType ExpectedResultType,
5629 CanQualType ExpectedFirstParamType,
5630 unsigned DependentParamTypeDiag,
5631 unsigned InvalidParamTypeDiag) {
5632 QualType ResultType =
5633 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5634
5635 // Check that the result type is not dependent.
5636 if (ResultType->isDependentType())
5637 return SemaRef.Diag(FnDecl->getLocation(),
5638 diag::err_operator_new_delete_dependent_result_type)
5639 << FnDecl->getDeclName() << ExpectedResultType;
5640
5641 // Check that the result type is what we expect.
5642 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5643 return SemaRef.Diag(FnDecl->getLocation(),
5644 diag::err_operator_new_delete_invalid_result_type)
5645 << FnDecl->getDeclName() << ExpectedResultType;
5646
5647 // A function template must have at least 2 parameters.
5648 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5649 return SemaRef.Diag(FnDecl->getLocation(),
5650 diag::err_operator_new_delete_template_too_few_parameters)
5651 << FnDecl->getDeclName();
5652
5653 // The function decl must have at least 1 parameter.
5654 if (FnDecl->getNumParams() == 0)
5655 return SemaRef.Diag(FnDecl->getLocation(),
5656 diag::err_operator_new_delete_too_few_parameters)
5657 << FnDecl->getDeclName();
5658
5659 // Check the the first parameter type is not dependent.
5660 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5661 if (FirstParamType->isDependentType())
5662 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5663 << FnDecl->getDeclName() << ExpectedFirstParamType;
5664
5665 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005666 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005667 ExpectedFirstParamType)
5668 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5669 << FnDecl->getDeclName() << ExpectedFirstParamType;
5670
5671 return false;
5672}
5673
Anders Carlsson12308f42009-12-11 23:23:22 +00005674static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005675CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005676 // C++ [basic.stc.dynamic.allocation]p1:
5677 // A program is ill-formed if an allocation function is declared in a
5678 // namespace scope other than global scope or declared static in global
5679 // scope.
5680 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5681 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005682
5683 CanQualType SizeTy =
5684 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5685
5686 // C++ [basic.stc.dynamic.allocation]p1:
5687 // The return type shall be void*. The first parameter shall have type
5688 // std::size_t.
5689 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5690 SizeTy,
5691 diag::err_operator_new_dependent_param_type,
5692 diag::err_operator_new_param_type))
5693 return true;
5694
5695 // C++ [basic.stc.dynamic.allocation]p1:
5696 // The first parameter shall not have an associated default argument.
5697 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005698 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005699 diag::err_operator_new_default_arg)
5700 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5701
5702 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005703}
5704
5705static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005706CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5707 // C++ [basic.stc.dynamic.deallocation]p1:
5708 // A program is ill-formed if deallocation functions are declared in a
5709 // namespace scope other than global scope or declared static in global
5710 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005711 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5712 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005713
5714 // C++ [basic.stc.dynamic.deallocation]p2:
5715 // Each deallocation function shall return void and its first parameter
5716 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005717 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5718 SemaRef.Context.VoidPtrTy,
5719 diag::err_operator_delete_dependent_param_type,
5720 diag::err_operator_delete_param_type))
5721 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005722
Anders Carlsson12308f42009-12-11 23:23:22 +00005723 return false;
5724}
5725
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005726/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5727/// of this overloaded operator is well-formed. If so, returns false;
5728/// otherwise, emits appropriate diagnostics and returns true.
5729bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005730 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005731 "Expected an overloaded operator declaration");
5732
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005733 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5734
Mike Stump11289f42009-09-09 15:08:12 +00005735 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005736 // The allocation and deallocation functions, operator new,
5737 // operator new[], operator delete and operator delete[], are
5738 // described completely in 3.7.3. The attributes and restrictions
5739 // found in the rest of this subclause do not apply to them unless
5740 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005741 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005742 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005743
Anders Carlsson22f443f2009-12-12 00:26:23 +00005744 if (Op == OO_New || Op == OO_Array_New)
5745 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005746
5747 // C++ [over.oper]p6:
5748 // An operator function shall either be a non-static member
5749 // function or be a non-member function and have at least one
5750 // parameter whose type is a class, a reference to a class, an
5751 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005752 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5753 if (MethodDecl->isStatic())
5754 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005755 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005756 } else {
5757 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005758 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5759 ParamEnd = FnDecl->param_end();
5760 Param != ParamEnd; ++Param) {
5761 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005762 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5763 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005764 ClassOrEnumParam = true;
5765 break;
5766 }
5767 }
5768
Douglas Gregord69246b2008-11-17 16:14:12 +00005769 if (!ClassOrEnumParam)
5770 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005771 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005772 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005773 }
5774
5775 // C++ [over.oper]p8:
5776 // An operator function cannot have default arguments (8.3.6),
5777 // except where explicitly stated below.
5778 //
Mike Stump11289f42009-09-09 15:08:12 +00005779 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005780 // (C++ [over.call]p1).
5781 if (Op != OO_Call) {
5782 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5783 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005784 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005785 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005786 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005787 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005788 }
5789 }
5790
Douglas Gregor6cf08062008-11-10 13:38:07 +00005791 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5792 { false, false, false }
5793#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5794 , { Unary, Binary, MemberOnly }
5795#include "clang/Basic/OperatorKinds.def"
5796 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005797
Douglas Gregor6cf08062008-11-10 13:38:07 +00005798 bool CanBeUnaryOperator = OperatorUses[Op][0];
5799 bool CanBeBinaryOperator = OperatorUses[Op][1];
5800 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005801
5802 // C++ [over.oper]p8:
5803 // [...] Operator functions cannot have more or fewer parameters
5804 // than the number required for the corresponding operator, as
5805 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005806 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005807 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005808 if (Op != OO_Call &&
5809 ((NumParams == 1 && !CanBeUnaryOperator) ||
5810 (NumParams == 2 && !CanBeBinaryOperator) ||
5811 (NumParams < 1) || (NumParams > 2))) {
5812 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005813 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005814 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005815 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005816 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005817 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005818 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005819 assert(CanBeBinaryOperator &&
5820 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005821 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005822 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005823
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005824 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005825 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005826 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005827
Douglas Gregord69246b2008-11-17 16:14:12 +00005828 // Overloaded operators other than operator() cannot be variadic.
5829 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005830 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005831 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005832 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005833 }
5834
5835 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005836 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5837 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005838 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005839 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005840 }
5841
5842 // C++ [over.inc]p1:
5843 // The user-defined function called operator++ implements the
5844 // prefix and postfix ++ operator. If this function is a member
5845 // function with no parameters, or a non-member function with one
5846 // parameter of class or enumeration type, it defines the prefix
5847 // increment operator ++ for objects of that type. If the function
5848 // is a member function with one parameter (which shall be of type
5849 // int) or a non-member function with two parameters (the second
5850 // of which shall be of type int), it defines the postfix
5851 // increment operator ++ for objects of that type.
5852 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5853 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5854 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005855 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005856 ParamIsInt = BT->getKind() == BuiltinType::Int;
5857
Chris Lattner2b786902008-11-21 07:50:02 +00005858 if (!ParamIsInt)
5859 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005860 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005861 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005862 }
5863
Douglas Gregord69246b2008-11-17 16:14:12 +00005864 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005865}
Chris Lattner3b024a32008-12-17 07:09:26 +00005866
Alexis Huntc88db062010-01-13 09:01:02 +00005867/// CheckLiteralOperatorDeclaration - Check whether the declaration
5868/// of this literal operator function is well-formed. If so, returns
5869/// false; otherwise, emits appropriate diagnostics and returns true.
5870bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5871 DeclContext *DC = FnDecl->getDeclContext();
5872 Decl::Kind Kind = DC->getDeclKind();
5873 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5874 Kind != Decl::LinkageSpec) {
5875 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5876 << FnDecl->getDeclName();
5877 return true;
5878 }
5879
5880 bool Valid = false;
5881
Alexis Hunt7dd26172010-04-07 23:11:06 +00005882 // template <char...> type operator "" name() is the only valid template
5883 // signature, and the only valid signature with no parameters.
5884 if (FnDecl->param_size() == 0) {
5885 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5886 // Must have only one template parameter
5887 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5888 if (Params->size() == 1) {
5889 NonTypeTemplateParmDecl *PmDecl =
5890 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005891
Alexis Hunt7dd26172010-04-07 23:11:06 +00005892 // The template parameter must be a char parameter pack.
5893 // FIXME: This test will always fail because non-type parameter packs
5894 // have not been implemented.
5895 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5896 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5897 Valid = true;
5898 }
5899 }
5900 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005901 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005902 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5903
Alexis Huntc88db062010-01-13 09:01:02 +00005904 QualType T = (*Param)->getType();
5905
Alexis Hunt079a6f72010-04-07 22:57:35 +00005906 // unsigned long long int, long double, and any character type are allowed
5907 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005908 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5909 Context.hasSameType(T, Context.LongDoubleTy) ||
5910 Context.hasSameType(T, Context.CharTy) ||
5911 Context.hasSameType(T, Context.WCharTy) ||
5912 Context.hasSameType(T, Context.Char16Ty) ||
5913 Context.hasSameType(T, Context.Char32Ty)) {
5914 if (++Param == FnDecl->param_end())
5915 Valid = true;
5916 goto FinishedParams;
5917 }
5918
Alexis Hunt079a6f72010-04-07 22:57:35 +00005919 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005920 const PointerType *PT = T->getAs<PointerType>();
5921 if (!PT)
5922 goto FinishedParams;
5923 T = PT->getPointeeType();
5924 if (!T.isConstQualified())
5925 goto FinishedParams;
5926 T = T.getUnqualifiedType();
5927
5928 // Move on to the second parameter;
5929 ++Param;
5930
5931 // If there is no second parameter, the first must be a const char *
5932 if (Param == FnDecl->param_end()) {
5933 if (Context.hasSameType(T, Context.CharTy))
5934 Valid = true;
5935 goto FinishedParams;
5936 }
5937
5938 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5939 // are allowed as the first parameter to a two-parameter function
5940 if (!(Context.hasSameType(T, Context.CharTy) ||
5941 Context.hasSameType(T, Context.WCharTy) ||
5942 Context.hasSameType(T, Context.Char16Ty) ||
5943 Context.hasSameType(T, Context.Char32Ty)))
5944 goto FinishedParams;
5945
5946 // The second and final parameter must be an std::size_t
5947 T = (*Param)->getType().getUnqualifiedType();
5948 if (Context.hasSameType(T, Context.getSizeType()) &&
5949 ++Param == FnDecl->param_end())
5950 Valid = true;
5951 }
5952
5953 // FIXME: This diagnostic is absolutely terrible.
5954FinishedParams:
5955 if (!Valid) {
5956 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5957 << FnDecl->getDeclName();
5958 return true;
5959 }
5960
5961 return false;
5962}
5963
Douglas Gregor07665a62009-01-05 19:45:36 +00005964/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5965/// linkage specification, including the language and (if present)
5966/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5967/// the location of the language string literal, which is provided
5968/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5969/// the '{' brace. Otherwise, this linkage specification does not
5970/// have any braces.
John McCall48871652010-08-21 09:40:31 +00005971Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005972 SourceLocation ExternLoc,
5973 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005974 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005975 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005976 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005977 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005978 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005979 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005980 Language = LinkageSpecDecl::lang_cxx;
5981 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005982 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00005983 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00005984 }
Mike Stump11289f42009-09-09 15:08:12 +00005985
Chris Lattner438e5012008-12-17 07:13:27 +00005986 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005987
Douglas Gregor07665a62009-01-05 19:45:36 +00005988 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005989 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005990 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005991 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005992 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00005993 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00005994}
5995
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00005996/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00005997/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5998/// valid, it's the position of the closing '}' brace in a linkage
5999/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006000Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6001 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006002 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006003 if (LinkageSpec)
6004 PopDeclContext();
6005 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006006}
6007
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006008/// \brief Perform semantic analysis for the variable declaration that
6009/// occurs within a C++ catch clause, returning the newly-created
6010/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006011VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006012 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006013 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006014 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006015 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006016 QualType ExDeclType = TInfo->getType();
6017
Sebastian Redl54c04d42008-12-22 19:15:10 +00006018 // Arrays and functions decay.
6019 if (ExDeclType->isArrayType())
6020 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6021 else if (ExDeclType->isFunctionType())
6022 ExDeclType = Context.getPointerType(ExDeclType);
6023
6024 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6025 // The exception-declaration shall not denote a pointer or reference to an
6026 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006027 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006028 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006029 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006030 Invalid = true;
6031 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006032
Douglas Gregor104ee002010-03-08 01:47:36 +00006033 // GCC allows catching pointers and references to incomplete types
6034 // as an extension; so do we, but we warn by default.
6035
Sebastian Redl54c04d42008-12-22 19:15:10 +00006036 QualType BaseType = ExDeclType;
6037 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006038 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006039 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006040 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006041 BaseType = Ptr->getPointeeType();
6042 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006043 DK = diag::ext_catch_incomplete_ptr;
6044 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006045 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006046 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006047 BaseType = Ref->getPointeeType();
6048 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006049 DK = diag::ext_catch_incomplete_ref;
6050 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006051 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006052 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006053 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6054 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006055 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006056
Mike Stump11289f42009-09-09 15:08:12 +00006057 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006058 RequireNonAbstractType(Loc, ExDeclType,
6059 diag::err_abstract_type_in_decl,
6060 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006061 Invalid = true;
6062
John McCall2ca705e2010-07-24 00:37:23 +00006063 // Only the non-fragile NeXT runtime currently supports C++ catches
6064 // of ObjC types, and no runtime supports catching ObjC types by value.
6065 if (!Invalid && getLangOptions().ObjC1) {
6066 QualType T = ExDeclType;
6067 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6068 T = RT->getPointeeType();
6069
6070 if (T->isObjCObjectType()) {
6071 Diag(Loc, diag::err_objc_object_catch);
6072 Invalid = true;
6073 } else if (T->isObjCObjectPointerType()) {
6074 if (!getLangOptions().NeXTRuntime) {
6075 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6076 Invalid = true;
6077 } else if (!getLangOptions().ObjCNonFragileABI) {
6078 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6079 Invalid = true;
6080 }
6081 }
6082 }
6083
Mike Stump11289f42009-09-09 15:08:12 +00006084 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006085 Name, ExDeclType, TInfo, SC_None,
6086 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006087 ExDecl->setExceptionVariable(true);
6088
Douglas Gregor6de584c2010-03-05 23:38:39 +00006089 if (!Invalid) {
6090 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6091 // C++ [except.handle]p16:
6092 // The object declared in an exception-declaration or, if the
6093 // exception-declaration does not specify a name, a temporary (12.2) is
6094 // copy-initialized (8.5) from the exception object. [...]
6095 // The object is destroyed when the handler exits, after the destruction
6096 // of any automatic objects initialized within the handler.
6097 //
6098 // We just pretend to initialize the object with itself, then make sure
6099 // it can be destroyed later.
6100 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6101 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6102 Loc, ExDeclType, 0);
6103 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6104 SourceLocation());
6105 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006106 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006107 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006108 if (Result.isInvalid())
6109 Invalid = true;
6110 else
6111 FinalizeVarWithDestructor(ExDecl, RecordTy);
6112 }
6113 }
6114
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006115 if (Invalid)
6116 ExDecl->setInvalidDecl();
6117
6118 return ExDecl;
6119}
6120
6121/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6122/// handler.
John McCall48871652010-08-21 09:40:31 +00006123Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006124 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6125 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006126
6127 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006128 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006129 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006130 LookupOrdinaryName,
6131 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006132 // The scope should be freshly made just for us. There is just no way
6133 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006134 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006135 if (PrevDecl->isTemplateParameter()) {
6136 // Maybe we will complain about the shadowed template parameter.
6137 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006138 }
6139 }
6140
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006141 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006142 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6143 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006144 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006145 }
6146
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006147 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006148 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006149 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006150
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006151 if (Invalid)
6152 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006153
Sebastian Redl54c04d42008-12-22 19:15:10 +00006154 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006155 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006156 PushOnScopeChains(ExDecl, S);
6157 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006158 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006159
Douglas Gregor758a8692009-06-17 21:51:59 +00006160 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006161 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006162}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006163
John McCall48871652010-08-21 09:40:31 +00006164Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006165 Expr *AssertExpr,
6166 Expr *AssertMessageExpr_) {
6167 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006168
Anders Carlsson54b26982009-03-14 00:33:21 +00006169 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6170 llvm::APSInt Value(32);
6171 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6172 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6173 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006174 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006175 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006176
Anders Carlsson54b26982009-03-14 00:33:21 +00006177 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006178 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006179 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006180 }
6181 }
Mike Stump11289f42009-09-09 15:08:12 +00006182
Mike Stump11289f42009-09-09 15:08:12 +00006183 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006184 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006185
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006186 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006187 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006188}
Sebastian Redlf769df52009-03-24 22:27:57 +00006189
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006190/// \brief Perform semantic analysis of the given friend type declaration.
6191///
6192/// \returns A friend declaration that.
6193FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6194 TypeSourceInfo *TSInfo) {
6195 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6196
6197 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006198 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006199
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006200 if (!getLangOptions().CPlusPlus0x) {
6201 // C++03 [class.friend]p2:
6202 // An elaborated-type-specifier shall be used in a friend declaration
6203 // for a class.*
6204 //
6205 // * The class-key of the elaborated-type-specifier is required.
6206 if (!ActiveTemplateInstantiations.empty()) {
6207 // Do not complain about the form of friend template types during
6208 // template instantiation; we will already have complained when the
6209 // template was declared.
6210 } else if (!T->isElaboratedTypeSpecifier()) {
6211 // If we evaluated the type to a record type, suggest putting
6212 // a tag in front.
6213 if (const RecordType *RT = T->getAs<RecordType>()) {
6214 RecordDecl *RD = RT->getDecl();
6215
6216 std::string InsertionText = std::string(" ") + RD->getKindName();
6217
6218 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6219 << (unsigned) RD->getTagKind()
6220 << T
6221 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6222 InsertionText);
6223 } else {
6224 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6225 << T
6226 << SourceRange(FriendLoc, TypeRange.getEnd());
6227 }
6228 } else if (T->getAs<EnumType>()) {
6229 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006230 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006231 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006232 }
6233 }
6234
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006235 // C++0x [class.friend]p3:
6236 // If the type specifier in a friend declaration designates a (possibly
6237 // cv-qualified) class type, that class is declared as a friend; otherwise,
6238 // the friend declaration is ignored.
6239
6240 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6241 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006242
6243 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6244}
6245
John McCallace48cd2010-10-19 01:40:49 +00006246/// Handle a friend tag declaration where the scope specifier was
6247/// templated.
6248Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6249 unsigned TagSpec, SourceLocation TagLoc,
6250 CXXScopeSpec &SS,
6251 IdentifierInfo *Name, SourceLocation NameLoc,
6252 AttributeList *Attr,
6253 MultiTemplateParamsArg TempParamLists) {
6254 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6255
6256 bool isExplicitSpecialization = false;
6257 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6258 bool Invalid = false;
6259
6260 if (TemplateParameterList *TemplateParams
6261 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6262 TempParamLists.get(),
6263 TempParamLists.size(),
6264 /*friend*/ true,
6265 isExplicitSpecialization,
6266 Invalid)) {
6267 --NumMatchedTemplateParamLists;
6268
6269 if (TemplateParams->size() > 0) {
6270 // This is a declaration of a class template.
6271 if (Invalid)
6272 return 0;
6273
6274 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6275 SS, Name, NameLoc, Attr,
6276 TemplateParams, AS_public).take();
6277 } else {
6278 // The "template<>" header is extraneous.
6279 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6280 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6281 isExplicitSpecialization = true;
6282 }
6283 }
6284
6285 if (Invalid) return 0;
6286
6287 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6288
6289 bool isAllExplicitSpecializations = true;
6290 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6291 if (TempParamLists.get()[I]->size()) {
6292 isAllExplicitSpecializations = false;
6293 break;
6294 }
6295 }
6296
6297 // FIXME: don't ignore attributes.
6298
6299 // If it's explicit specializations all the way down, just forget
6300 // about the template header and build an appropriate non-templated
6301 // friend. TODO: for source fidelity, remember the headers.
6302 if (isAllExplicitSpecializations) {
6303 ElaboratedTypeKeyword Keyword
6304 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6305 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6306 TagLoc, SS.getRange(), NameLoc);
6307 if (T.isNull())
6308 return 0;
6309
6310 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6311 if (isa<DependentNameType>(T)) {
6312 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6313 TL.setKeywordLoc(TagLoc);
6314 TL.setQualifierRange(SS.getRange());
6315 TL.setNameLoc(NameLoc);
6316 } else {
6317 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6318 TL.setKeywordLoc(TagLoc);
6319 TL.setQualifierRange(SS.getRange());
6320 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6321 }
6322
6323 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6324 TSI, FriendLoc);
6325 Friend->setAccess(AS_public);
6326 CurContext->addDecl(Friend);
6327 return Friend;
6328 }
6329
6330 // Handle the case of a templated-scope friend class. e.g.
6331 // template <class T> class A<T>::B;
6332 // FIXME: we don't support these right now.
6333 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6334 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6335 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6336 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6337 TL.setKeywordLoc(TagLoc);
6338 TL.setQualifierRange(SS.getRange());
6339 TL.setNameLoc(NameLoc);
6340
6341 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6342 TSI, FriendLoc);
6343 Friend->setAccess(AS_public);
6344 Friend->setUnsupportedFriend(true);
6345 CurContext->addDecl(Friend);
6346 return Friend;
6347}
6348
6349
John McCall11083da2009-09-16 22:47:08 +00006350/// Handle a friend type declaration. This works in tandem with
6351/// ActOnTag.
6352///
6353/// Notes on friend class templates:
6354///
6355/// We generally treat friend class declarations as if they were
6356/// declaring a class. So, for example, the elaborated type specifier
6357/// in a friend declaration is required to obey the restrictions of a
6358/// class-head (i.e. no typedefs in the scope chain), template
6359/// parameters are required to match up with simple template-ids, &c.
6360/// However, unlike when declaring a template specialization, it's
6361/// okay to refer to a template specialization without an empty
6362/// template parameter declaration, e.g.
6363/// friend class A<T>::B<unsigned>;
6364/// We permit this as a special case; if there are any template
6365/// parameters present at all, require proper matching, i.e.
6366/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006367Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006368 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006369 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006370
6371 assert(DS.isFriendSpecified());
6372 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6373
John McCall11083da2009-09-16 22:47:08 +00006374 // Try to convert the decl specifier to a type. This works for
6375 // friend templates because ActOnTag never produces a ClassTemplateDecl
6376 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006377 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006378 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6379 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006380 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006381 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006382
John McCall11083da2009-09-16 22:47:08 +00006383 // This is definitely an error in C++98. It's probably meant to
6384 // be forbidden in C++0x, too, but the specification is just
6385 // poorly written.
6386 //
6387 // The problem is with declarations like the following:
6388 // template <T> friend A<T>::foo;
6389 // where deciding whether a class C is a friend or not now hinges
6390 // on whether there exists an instantiation of A that causes
6391 // 'foo' to equal C. There are restrictions on class-heads
6392 // (which we declare (by fiat) elaborated friend declarations to
6393 // be) that makes this tractable.
6394 //
6395 // FIXME: handle "template <> friend class A<T>;", which
6396 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006397 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006398 Diag(Loc, diag::err_tagless_friend_type_template)
6399 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006400 return 0;
John McCall11083da2009-09-16 22:47:08 +00006401 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006402
John McCallaa74a0c2009-08-28 07:59:38 +00006403 // C++98 [class.friend]p1: A friend of a class is a function
6404 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006405 // This is fixed in DR77, which just barely didn't make the C++03
6406 // deadline. It's also a very silly restriction that seriously
6407 // affects inner classes and which nobody else seems to implement;
6408 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006409 //
6410 // But note that we could warn about it: it's always useless to
6411 // friend one of your own members (it's not, however, worthless to
6412 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006413
John McCall11083da2009-09-16 22:47:08 +00006414 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006415 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006416 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006417 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006418 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006419 TSI,
John McCall11083da2009-09-16 22:47:08 +00006420 DS.getFriendSpecLoc());
6421 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006422 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6423
6424 if (!D)
John McCall48871652010-08-21 09:40:31 +00006425 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006426
John McCall11083da2009-09-16 22:47:08 +00006427 D->setAccess(AS_public);
6428 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006429
John McCall48871652010-08-21 09:40:31 +00006430 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006431}
6432
John McCallde3fd222010-10-12 23:13:28 +00006433Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6434 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006435 const DeclSpec &DS = D.getDeclSpec();
6436
6437 assert(DS.isFriendSpecified());
6438 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6439
6440 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006441 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6442 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006443
6444 // C++ [class.friend]p1
6445 // A friend of a class is a function or class....
6446 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006447 // It *doesn't* see through dependent types, which is correct
6448 // according to [temp.arg.type]p3:
6449 // If a declaration acquires a function type through a
6450 // type dependent on a template-parameter and this causes
6451 // a declaration that does not use the syntactic form of a
6452 // function declarator to have a function type, the program
6453 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006454 if (!T->isFunctionType()) {
6455 Diag(Loc, diag::err_unexpected_friend);
6456
6457 // It might be worthwhile to try to recover by creating an
6458 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006459 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006460 }
6461
6462 // C++ [namespace.memdef]p3
6463 // - If a friend declaration in a non-local class first declares a
6464 // class or function, the friend class or function is a member
6465 // of the innermost enclosing namespace.
6466 // - The name of the friend is not found by simple name lookup
6467 // until a matching declaration is provided in that namespace
6468 // scope (either before or after the class declaration granting
6469 // friendship).
6470 // - If a friend function is called, its name may be found by the
6471 // name lookup that considers functions from namespaces and
6472 // classes associated with the types of the function arguments.
6473 // - When looking for a prior declaration of a class or a function
6474 // declared as a friend, scopes outside the innermost enclosing
6475 // namespace scope are not considered.
6476
John McCallde3fd222010-10-12 23:13:28 +00006477 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006478 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6479 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006480 assert(Name);
6481
John McCall07e91c02009-08-06 02:15:43 +00006482 // The context we found the declaration in, or in which we should
6483 // create the declaration.
6484 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006485 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006486 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006487 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006488
John McCallde3fd222010-10-12 23:13:28 +00006489 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006490
John McCallde3fd222010-10-12 23:13:28 +00006491 // There are four cases here.
6492 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006493 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006494 // there as appropriate.
6495 // Recover from invalid scope qualifiers as if they just weren't there.
6496 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006497 // C++0x [namespace.memdef]p3:
6498 // If the name in a friend declaration is neither qualified nor
6499 // a template-id and the declaration is a function or an
6500 // elaborated-type-specifier, the lookup to determine whether
6501 // the entity has been previously declared shall not consider
6502 // any scopes outside the innermost enclosing namespace.
6503 // C++0x [class.friend]p11:
6504 // If a friend declaration appears in a local class and the name
6505 // specified is an unqualified name, a prior declaration is
6506 // looked up without considering scopes that are outside the
6507 // innermost enclosing non-class scope. For a friend function
6508 // declaration, if there is no prior declaration, the program is
6509 // ill-formed.
6510 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006511 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006512
John McCallf7cfb222010-10-13 05:45:15 +00006513 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006514 DC = CurContext;
6515 while (true) {
6516 // Skip class contexts. If someone can cite chapter and verse
6517 // for this behavior, that would be nice --- it's what GCC and
6518 // EDG do, and it seems like a reasonable intent, but the spec
6519 // really only says that checks for unqualified existing
6520 // declarations should stop at the nearest enclosing namespace,
6521 // not that they should only consider the nearest enclosing
6522 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006523 while (DC->isRecord())
6524 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006525
John McCall1f82f242009-11-18 22:49:29 +00006526 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006527
6528 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006529 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006530 break;
John McCallf7cfb222010-10-13 05:45:15 +00006531
John McCallf4776592010-10-14 22:22:28 +00006532 if (isTemplateId) {
6533 if (isa<TranslationUnitDecl>(DC)) break;
6534 } else {
6535 if (DC->isFileContext()) break;
6536 }
John McCall07e91c02009-08-06 02:15:43 +00006537 DC = DC->getParent();
6538 }
6539
6540 // C++ [class.friend]p1: A friend of a class is a function or
6541 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006542 // C++0x changes this for both friend types and functions.
6543 // Most C++ 98 compilers do seem to give an error here, so
6544 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006545 if (!Previous.empty() && DC->Equals(CurContext)
6546 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006547 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006548
John McCallccbc0322010-10-13 06:22:15 +00006549 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006550
John McCallde3fd222010-10-12 23:13:28 +00006551 // - There's a non-dependent scope specifier, in which case we
6552 // compute it and do a previous lookup there for a function
6553 // or function template.
6554 } else if (!SS.getScopeRep()->isDependent()) {
6555 DC = computeDeclContext(SS);
6556 if (!DC) return 0;
6557
6558 if (RequireCompleteDeclContext(SS, DC)) return 0;
6559
6560 LookupQualifiedName(Previous, DC);
6561
6562 // Ignore things found implicitly in the wrong scope.
6563 // TODO: better diagnostics for this case. Suggesting the right
6564 // qualified scope would be nice...
6565 LookupResult::Filter F = Previous.makeFilter();
6566 while (F.hasNext()) {
6567 NamedDecl *D = F.next();
6568 if (!DC->InEnclosingNamespaceSetOf(
6569 D->getDeclContext()->getRedeclContext()))
6570 F.erase();
6571 }
6572 F.done();
6573
6574 if (Previous.empty()) {
6575 D.setInvalidType();
6576 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6577 return 0;
6578 }
6579
6580 // C++ [class.friend]p1: A friend of a class is a function or
6581 // class that is not a member of the class . . .
6582 if (DC->Equals(CurContext))
6583 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6584
6585 // - There's a scope specifier that does not match any template
6586 // parameter lists, in which case we use some arbitrary context,
6587 // create a method or method template, and wait for instantiation.
6588 // - There's a scope specifier that does match some template
6589 // parameter lists, which we don't handle right now.
6590 } else {
6591 DC = CurContext;
6592 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006593 }
6594
John McCallf7cfb222010-10-13 05:45:15 +00006595 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006596 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006597 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6598 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6599 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006600 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006601 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6602 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006603 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006604 }
John McCall07e91c02009-08-06 02:15:43 +00006605 }
6606
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006607 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006608 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006609 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006610 IsDefinition,
6611 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006612 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006613
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006614 assert(ND->getDeclContext() == DC);
6615 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006616
John McCall759e32b2009-08-31 22:39:49 +00006617 // Add the function declaration to the appropriate lookup tables,
6618 // adjusting the redeclarations list as necessary. We don't
6619 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006620 //
John McCall759e32b2009-08-31 22:39:49 +00006621 // Also update the scope-based lookup if the target context's
6622 // lookup context is in lexical scope.
6623 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006624 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006625 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006626 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006627 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006628 }
John McCallaa74a0c2009-08-28 07:59:38 +00006629
6630 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006631 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006632 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006633 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006634 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006635
John McCallde3fd222010-10-12 23:13:28 +00006636 if (ND->isInvalidDecl())
6637 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006638 else {
6639 FunctionDecl *FD;
6640 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6641 FD = FTD->getTemplatedDecl();
6642 else
6643 FD = cast<FunctionDecl>(ND);
6644
6645 // Mark templated-scope function declarations as unsupported.
6646 if (FD->getNumTemplateParameterLists())
6647 FrD->setUnsupportedFriend(true);
6648 }
John McCallde3fd222010-10-12 23:13:28 +00006649
John McCall48871652010-08-21 09:40:31 +00006650 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006651}
6652
John McCall48871652010-08-21 09:40:31 +00006653void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6654 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006655
Sebastian Redlf769df52009-03-24 22:27:57 +00006656 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6657 if (!Fn) {
6658 Diag(DelLoc, diag::err_deleted_non_function);
6659 return;
6660 }
6661 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6662 Diag(DelLoc, diag::err_deleted_decl_not_first);
6663 Diag(Prev->getLocation(), diag::note_previous_declaration);
6664 // If the declaration wasn't the first, we delete the function anyway for
6665 // recovery.
6666 }
6667 Fn->setDeleted();
6668}
Sebastian Redl4c018662009-04-27 21:33:24 +00006669
6670static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6671 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6672 ++CI) {
6673 Stmt *SubStmt = *CI;
6674 if (!SubStmt)
6675 continue;
6676 if (isa<ReturnStmt>(SubStmt))
6677 Self.Diag(SubStmt->getSourceRange().getBegin(),
6678 diag::err_return_in_constructor_handler);
6679 if (!isa<Expr>(SubStmt))
6680 SearchForReturnInStmt(Self, SubStmt);
6681 }
6682}
6683
6684void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6685 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6686 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6687 SearchForReturnInStmt(*this, Handler);
6688 }
6689}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006690
Mike Stump11289f42009-09-09 15:08:12 +00006691bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006692 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006693 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6694 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006695
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006696 if (Context.hasSameType(NewTy, OldTy) ||
6697 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006698 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006699
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006700 // Check if the return types are covariant
6701 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006702
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006703 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006704 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6705 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006706 NewClassTy = NewPT->getPointeeType();
6707 OldClassTy = OldPT->getPointeeType();
6708 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006709 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6710 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6711 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6712 NewClassTy = NewRT->getPointeeType();
6713 OldClassTy = OldRT->getPointeeType();
6714 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006715 }
6716 }
Mike Stump11289f42009-09-09 15:08:12 +00006717
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006718 // The return types aren't either both pointers or references to a class type.
6719 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006720 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006721 diag::err_different_return_type_for_overriding_virtual_function)
6722 << New->getDeclName() << NewTy << OldTy;
6723 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006724
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006725 return true;
6726 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006727
Anders Carlssone60365b2009-12-31 18:34:24 +00006728 // C++ [class.virtual]p6:
6729 // If the return type of D::f differs from the return type of B::f, the
6730 // class type in the return type of D::f shall be complete at the point of
6731 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006732 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6733 if (!RT->isBeingDefined() &&
6734 RequireCompleteType(New->getLocation(), NewClassTy,
6735 PDiag(diag::err_covariant_return_incomplete)
6736 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006737 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006738 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006739
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006740 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006741 // Check if the new class derives from the old class.
6742 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6743 Diag(New->getLocation(),
6744 diag::err_covariant_return_not_derived)
6745 << New->getDeclName() << NewTy << OldTy;
6746 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6747 return true;
6748 }
Mike Stump11289f42009-09-09 15:08:12 +00006749
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006750 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006751 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006752 diag::err_covariant_return_inaccessible_base,
6753 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6754 // FIXME: Should this point to the return type?
6755 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006756 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6757 return true;
6758 }
6759 }
Mike Stump11289f42009-09-09 15:08:12 +00006760
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006761 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006762 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006763 Diag(New->getLocation(),
6764 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006765 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006766 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6767 return true;
6768 };
Mike Stump11289f42009-09-09 15:08:12 +00006769
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006770
6771 // The new class type must have the same or less qualifiers as the old type.
6772 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6773 Diag(New->getLocation(),
6774 diag::err_covariant_return_type_class_type_more_qualified)
6775 << New->getDeclName() << NewTy << OldTy;
6776 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6777 return true;
6778 };
Mike Stump11289f42009-09-09 15:08:12 +00006779
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006780 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006781}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006782
Alexis Hunt96d5c762009-11-21 08:43:09 +00006783bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6784 const CXXMethodDecl *Old)
6785{
6786 if (Old->hasAttr<FinalAttr>()) {
6787 Diag(New->getLocation(), diag::err_final_function_overridden)
6788 << New->getDeclName();
6789 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6790 return true;
6791 }
6792
6793 return false;
6794}
6795
Douglas Gregor21920e372009-12-01 17:24:26 +00006796/// \brief Mark the given method pure.
6797///
6798/// \param Method the method to be marked pure.
6799///
6800/// \param InitRange the source range that covers the "0" initializer.
6801bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6802 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6803 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006804 return false;
6805 }
6806
6807 if (!Method->isInvalidDecl())
6808 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6809 << Method->getDeclName() << InitRange;
6810 return true;
6811}
6812
John McCall1f4ee7b2009-12-19 09:28:58 +00006813/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6814/// an initializer for the out-of-line declaration 'Dcl'. The scope
6815/// is a fresh scope pushed for just this purpose.
6816///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006817/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6818/// static data member of class X, names should be looked up in the scope of
6819/// class X.
John McCall48871652010-08-21 09:40:31 +00006820void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006821 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006822 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006823
John McCall1f4ee7b2009-12-19 09:28:58 +00006824 // We should only get called for declarations with scope specifiers, like:
6825 // int foo::bar;
6826 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006827 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006828}
6829
6830/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006831/// initializer for the out-of-line declaration 'D'.
6832void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006833 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006834 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006835
John McCall1f4ee7b2009-12-19 09:28:58 +00006836 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006837 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006838}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006839
6840/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6841/// C++ if/switch/while/for statement.
6842/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006843DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006844 // C++ 6.4p2:
6845 // The declarator shall not specify a function or an array.
6846 // The type-specifier-seq shall not contain typedef and shall not declare a
6847 // new class or enumeration.
6848 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6849 "Parser allowed 'typedef' as storage class of condition decl.");
6850
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006851 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006852 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6853 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006854
6855 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6856 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6857 // would be created and CXXConditionDeclExpr wants a VarDecl.
6858 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6859 << D.getSourceRange();
6860 return DeclResult();
6861 } else if (OwnedTag && OwnedTag->isDefinition()) {
6862 // The type-specifier-seq shall not declare a new class or enumeration.
6863 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6864 }
6865
John McCall48871652010-08-21 09:40:31 +00006866 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006867 if (!Dcl)
6868 return DeclResult();
6869
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006870 return Dcl;
6871}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006872
Douglas Gregor88d292c2010-05-13 16:44:06 +00006873void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6874 bool DefinitionRequired) {
6875 // Ignore any vtable uses in unevaluated operands or for classes that do
6876 // not have a vtable.
6877 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6878 CurContext->isDependentContext() ||
6879 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006880 return;
6881
Douglas Gregor88d292c2010-05-13 16:44:06 +00006882 // Try to insert this class into the map.
6883 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6884 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6885 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6886 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006887 // If we already had an entry, check to see if we are promoting this vtable
6888 // to required a definition. If so, we need to reappend to the VTableUses
6889 // list, since we may have already processed the first entry.
6890 if (DefinitionRequired && !Pos.first->second) {
6891 Pos.first->second = true;
6892 } else {
6893 // Otherwise, we can early exit.
6894 return;
6895 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006896 }
6897
6898 // Local classes need to have their virtual members marked
6899 // immediately. For all other classes, we mark their virtual members
6900 // at the end of the translation unit.
6901 if (Class->isLocalClass())
6902 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006903 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006904 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006905}
6906
Douglas Gregor88d292c2010-05-13 16:44:06 +00006907bool Sema::DefineUsedVTables() {
6908 // If any dynamic classes have their key function defined within
6909 // this translation unit, then those vtables are considered "used" and must
6910 // be emitted.
6911 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6912 if (const CXXMethodDecl *KeyFunction
6913 = Context.getKeyFunction(DynamicClasses[I])) {
6914 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006915 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006916 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6917 }
6918 }
6919
6920 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006921 return false;
6922
Douglas Gregor88d292c2010-05-13 16:44:06 +00006923 // Note: The VTableUses vector could grow as a result of marking
6924 // the members of a class as "used", so we check the size each
6925 // time through the loop and prefer indices (with are stable) to
6926 // iterators (which are not).
6927 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006928 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006929 if (!Class)
6930 continue;
6931
6932 SourceLocation Loc = VTableUses[I].second;
6933
6934 // If this class has a key function, but that key function is
6935 // defined in another translation unit, we don't need to emit the
6936 // vtable even though we're using it.
6937 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006938 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006939 switch (KeyFunction->getTemplateSpecializationKind()) {
6940 case TSK_Undeclared:
6941 case TSK_ExplicitSpecialization:
6942 case TSK_ExplicitInstantiationDeclaration:
6943 // The key function is in another translation unit.
6944 continue;
6945
6946 case TSK_ExplicitInstantiationDefinition:
6947 case TSK_ImplicitInstantiation:
6948 // We will be instantiating the key function.
6949 break;
6950 }
6951 } else if (!KeyFunction) {
6952 // If we have a class with no key function that is the subject
6953 // of an explicit instantiation declaration, suppress the
6954 // vtable; it will live with the explicit instantiation
6955 // definition.
6956 bool IsExplicitInstantiationDeclaration
6957 = Class->getTemplateSpecializationKind()
6958 == TSK_ExplicitInstantiationDeclaration;
6959 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6960 REnd = Class->redecls_end();
6961 R != REnd; ++R) {
6962 TemplateSpecializationKind TSK
6963 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6964 if (TSK == TSK_ExplicitInstantiationDeclaration)
6965 IsExplicitInstantiationDeclaration = true;
6966 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6967 IsExplicitInstantiationDeclaration = false;
6968 break;
6969 }
6970 }
6971
6972 if (IsExplicitInstantiationDeclaration)
6973 continue;
6974 }
6975
6976 // Mark all of the virtual members of this class as referenced, so
6977 // that we can build a vtable. Then, tell the AST consumer that a
6978 // vtable for this class is required.
6979 MarkVirtualMembersReferenced(Loc, Class);
6980 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6981 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6982
6983 // Optionally warn if we're emitting a weak vtable.
6984 if (Class->getLinkage() == ExternalLinkage &&
6985 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006986 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006987 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6988 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006989 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006990 VTableUses.clear();
6991
Anders Carlsson82fccd02009-12-07 08:24:59 +00006992 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006993}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006994
Rafael Espindola5b334082010-03-26 00:36:59 +00006995void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6996 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006997 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6998 e = RD->method_end(); i != e; ++i) {
6999 CXXMethodDecl *MD = *i;
7000
7001 // C++ [basic.def.odr]p2:
7002 // [...] A virtual member function is used if it is not pure. [...]
7003 if (MD->isVirtual() && !MD->isPure())
7004 MarkDeclarationReferenced(Loc, MD);
7005 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007006
7007 // Only classes that have virtual bases need a VTT.
7008 if (RD->getNumVBases() == 0)
7009 return;
7010
7011 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7012 e = RD->bases_end(); i != e; ++i) {
7013 const CXXRecordDecl *Base =
7014 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007015 if (Base->getNumVBases() == 0)
7016 continue;
7017 MarkVirtualMembersReferenced(Loc, Base);
7018 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007019}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007020
7021/// SetIvarInitializers - This routine builds initialization ASTs for the
7022/// Objective-C implementation whose ivars need be initialized.
7023void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7024 if (!getLangOptions().CPlusPlus)
7025 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007026 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007027 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7028 CollectIvarsToConstructOrDestruct(OID, ivars);
7029 if (ivars.empty())
7030 return;
7031 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7032 for (unsigned i = 0; i < ivars.size(); i++) {
7033 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007034 if (Field->isInvalidDecl())
7035 continue;
7036
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007037 CXXBaseOrMemberInitializer *Member;
7038 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7039 InitializationKind InitKind =
7040 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7041
7042 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007043 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007044 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00007045 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007046 // Note, MemberInit could actually come back empty if no initialization
7047 // is required (e.g., because it would call a trivial default constructor)
7048 if (!MemberInit.get() || MemberInit.isInvalid())
7049 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007050
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007051 Member =
7052 new (Context) CXXBaseOrMemberInitializer(Context,
7053 Field, SourceLocation(),
7054 SourceLocation(),
7055 MemberInit.takeAs<Expr>(),
7056 SourceLocation());
7057 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007058
7059 // Be sure that the destructor is accessible and is marked as referenced.
7060 if (const RecordType *RecordTy
7061 = Context.getBaseElementType(Field->getType())
7062 ->getAs<RecordType>()) {
7063 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007064 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007065 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7066 CheckDestructorAccess(Field->getLocation(), Destructor,
7067 PDiag(diag::err_access_dtor_ivar)
7068 << Context.getBaseElementType(Field->getType()));
7069 }
7070 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007071 }
7072 ObjCImplementation->setIvarInitializers(Context,
7073 AllToInit.data(), AllToInit.size());
7074 }
7075}