blob: 8fe4852890d7bd0219697a9bce97a151074e2cb9 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregor752a5952011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Alexis Hunt96d5c762009-11-21 08:43:09 +0000524 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
525 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
526 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000531
John McCall3696dcb2010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539}
540
Douglas Gregor556877c2008-04-13 21:30:24 +0000541/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
542/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000546BaseResult
John McCall48871652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregorc40290e2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky19b9f952010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000561
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000573}
Douglas Gregor556877c2008-04-13 21:30:24 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575/// \brief Performs the actual work of attaching the given base class
576/// specifiers to a C++ class.
577bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
578 unsigned NumBases) {
579 if (NumBases == 0)
580 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000581
582 // Used to keep track of which base types we have already seen, so
583 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000595 if (!Class->hasObjectMember()) {
596 if (const RecordType *FDTTy =
597 NewBaseType.getTypePtr()->getAs<RecordType>())
598 if (FDTTy->getDecl()->hasObjectMember())
599 Class->setHasObjectMember(true);
600 }
601
Douglas Gregor29a92472008-10-22 17:49:05 +0000602 if (KnownBaseTypes[NewBaseType]) {
603 // C++ [class.mi]p3:
604 // A class shall not be specified as a direct base class of a
605 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
626 // Delete the remaining (good) base class specifiers, since their
627 // data has been copied into the CXXRecordDecl.
628 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000630
631 return Invalid;
632}
633
634/// ActOnBaseSpecifiers - Attach the given base specifiers to the
635/// class, after checking whether there are any duplicate base
636/// classes.
John McCall48871652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000646
John McCalle78aac42010-03-10 03:28:59 +0000647static CXXRecordDecl *GetClassForType(QualType T) {
648 if (const RecordType *RT = T->getAs<RecordType>())
649 return cast<CXXRecordDecl>(RT->getDecl());
650 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
651 return ICT->getDecl();
652 else
653 return 0;
654}
655
Douglas Gregor36d1b142009-10-06 17:59:45 +0000656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
John McCalle78aac42010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
John McCalle78aac42010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCall67da35c2010-02-04 22:26:26 +0000670 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
671 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672}
673
674/// \brief Determine whether the type \p Derived is a C++ class that is
675/// derived from the type \p Base.
676bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
677 if (!getLangOptions().CPlusPlus)
678 return false;
679
John McCalle78aac42010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlssona70cff62010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000693 assert(BasePathArray.empty() && "Base path array must be empty!");
694 assert(Paths.isRecordingPaths() && "Must record paths!");
695
696 const CXXBasePath &Path = Paths.front();
697
698 // We first go backward and check if we have a virtual base.
699 // FIXME: It would be better if CXXBasePath had the base specifier for
700 // the nearest virtual base.
701 unsigned Start = 0;
702 for (unsigned I = Path.size(); I != 0; --I) {
703 if (Path[I - 1].Base->isVirtual()) {
704 Start = I - 1;
705 break;
706 }
707 }
708
709 // Now add all bases.
710 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000712}
713
Douglas Gregor88d292c2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallcf142162010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregor36d1b142009-10-06 17:59:45 +0000726/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
727/// conversion (where Derived and Base are class types) is
728/// well-formed, meaning that the conversion is unambiguous (and
729/// that all of the base classes are accessible). Returns true
730/// and emits a diagnostic if the code is ill-formed, returns false
731/// otherwise. Loc is the location where this routine should point to
732/// if there is an error, and Range is the source range to highlight
733/// if there is an error.
734bool
735Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 // First, determine whether the path from Derived to Base is
742 // ambiguous. This is slightly more expensive than checking whether
743 // the Derived to Base conversion exists, because here we need to
744 // explore multiple paths to determine if there is an ambiguity.
745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
746 /*DetectVirtual=*/false);
747 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(DerivationOkay &&
749 "Can only be used with a derived-to-base conversion");
750 (void)DerivationOkay;
751
752 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000753 if (InaccessibleBaseID) {
754 // Check that the base class can be accessed.
755 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
756 InaccessibleBaseID)) {
757 case AR_inaccessible:
758 return true;
759 case AR_accessible:
760 case AR_dependent:
761 case AR_delayed:
762 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000763 }
John McCall5b0829a2010-02-10 09:31:12 +0000764 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000770 }
771
772 // We know that the derived-to-base conversion is ambiguous, and
773 // we're going to produce a diagnostic. Perform the derived-to-base
774 // search just one more time to compute all of the possible paths so
775 // that we can print them out. This is more expensive than any of
776 // the previous derived-to-base checks we've done, but at this point
777 // performance isn't as much of an issue.
778 Paths.clear();
779 Paths.setRecordingPaths(true);
780 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(StillOkay && "Can only be used with a derived-to-base conversion");
782 (void)StillOkay;
783
784 // Build up a textual representation of the ambiguous paths, e.g.,
785 // D -> B -> A, that will be used to illustrate the ambiguous
786 // conversions in the diagnostic. We only print one of the paths
787 // to each base class subobject.
788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
789
790 Diag(Loc, AmbigiousBaseConvID)
791 << Derived << Base << PathDisplayStr << Range << Name;
792 return true;
793}
794
795bool
796Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806}
807
808
809/// @brief Builds a string representing ambiguous paths from a
810/// specific derived class to different subobjects of the same base
811/// class.
812///
813/// This function builds a string that can be used in error messages
814/// to show the different paths that one can take through the
815/// inheritance hierarchy to go from the derived class to different
816/// subobjects of a base class. The result looks something like this:
817/// @code
818/// struct D -> struct B -> struct A
819/// struct D -> struct C -> struct A
820/// @endcode
821std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
822 std::string PathDisplayStr;
823 std::set<unsigned> DisplayedPaths;
824 for (CXXBasePaths::paths_iterator Path = Paths.begin();
825 Path != Paths.end(); ++Path) {
826 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
827 // We haven't displayed a path to this particular base
828 // class subobject yet.
829 PathDisplayStr += "\n ";
830 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
831 for (CXXBasePath::const_iterator Element = Path->begin();
832 Element != Path->end(); ++Element)
833 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
834 }
835 }
836
837 return PathDisplayStr;
838}
839
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnarad7340582010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853}
854
Anders Carlssonfd835532011-01-20 05:57:14 +0000855/// CheckOverrideControl - Check C++0x override control semantics.
856static void
857CheckOverrideControl(Sema& SemaRef, const Decl *D) {
858 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
859 if (!MD || !MD->isVirtual())
860 return;
861
862 // C++0x [class.virtual]p3:
863 // If a virtual function is marked with the virt-specifier override and does
864 // not override a member function of a base class,
865 // the program is ill-formed.
866 bool HasOverriddenMethods =
867 MD->begin_overridden_methods() != MD->end_overridden_methods();
868 if (MD->isMarkedOverride() && !HasOverriddenMethods) {
869 SemaRef.Diag(MD->getLocation(),
870 diag::err_function_marked_override_not_overriding)
871 << MD->getDeclName();
872 return;
873 }
874}
875
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
877/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
878/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000879/// any.
John McCall48871652010-08-21 09:40:31 +0000880Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000881Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000882 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000883 ExprTy *BW, const VirtSpecifiers &VS,
884 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000885 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000886 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000887 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
888 DeclarationName Name = NameInfo.getName();
889 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000890
891 // For anonymous bitfields, the location should point to the type.
892 if (Loc.isInvalid())
893 Loc = D.getSourceRange().getBegin();
894
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000895 Expr *BitWidth = static_cast<Expr*>(BW);
896 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000897
John McCallb1cd7da2010-06-04 08:34:12 +0000898 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000899 assert(!DS.isFriendSpecified());
900
John McCallb1cd7da2010-06-04 08:34:12 +0000901 bool isFunc = false;
902 if (D.isFunctionDeclarator())
903 isFunc = true;
904 else if (D.getNumTypeObjects() == 0 &&
905 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000906 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000907 isFunc = TDType->isFunctionType();
908 }
909
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000910 // C++ 9.2p6: A member shall not be declared to have automatic storage
911 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000912 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
913 // data members and cannot be applied to names declared const or static,
914 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915 switch (DS.getStorageClassSpec()) {
916 case DeclSpec::SCS_unspecified:
917 case DeclSpec::SCS_typedef:
918 case DeclSpec::SCS_static:
919 // FALL THROUGH.
920 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000921 case DeclSpec::SCS_mutable:
922 if (isFunc) {
923 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000924 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000925 else
Chris Lattner3b054132008-11-19 05:08:23 +0000926 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000927
Sebastian Redl8071edb2008-11-17 23:24:37 +0000928 // FIXME: It would be nicer if the keyword was ignored only for this
929 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000930 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000931 }
932 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000933 default:
934 if (DS.getStorageClassSpecLoc().isValid())
935 Diag(DS.getStorageClassSpecLoc(),
936 diag::err_storageclass_invalid_for_member);
937 else
938 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
939 D.getMutableDeclSpec().ClearStorageClassSpecs();
940 }
941
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000942 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
943 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000944 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000945
946 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000947 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000948 CXXScopeSpec &SS = D.getCXXScopeSpec();
949
950
951 if (SS.isSet() && !SS.isInvalid()) {
952 // The user provided a superfluous scope specifier inside a class
953 // definition:
954 //
955 // class X {
956 // int X::member;
957 // };
958 DeclContext *DC = 0;
959 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
960 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
961 << Name << FixItHint::CreateRemoval(SS.getRange());
962 else
963 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
964 << Name << SS.getRange();
965
966 SS.clear();
967 }
968
Douglas Gregor3447e762009-08-20 22:52:58 +0000969 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000970 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000971 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
972 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000973 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000974 } else {
John McCall48871652010-08-21 09:40:31 +0000975 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000976 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000977 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000978 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000979
980 // Non-instance-fields can't have a bitfield.
981 if (BitWidth) {
982 if (Member->isInvalidDecl()) {
983 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000984 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000985 // C++ 9.6p3: A bit-field shall not be a static member.
986 // "static member 'A' cannot be a bit-field"
987 Diag(Loc, diag::err_static_not_bitfield)
988 << Name << BitWidth->getSourceRange();
989 } else if (isa<TypedefDecl>(Member)) {
990 // "typedef member 'x' cannot be a bit-field"
991 Diag(Loc, diag::err_typedef_not_bitfield)
992 << Name << BitWidth->getSourceRange();
993 } else {
994 // A function typedef ("typedef int f(); f a;").
995 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
996 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000997 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000998 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
Chris Lattnerd26760a2009-03-05 23:01:03 +00001001 BitWidth = 0;
1002 Member->setInvalidDecl();
1003 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001004
1005 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001006
Douglas Gregor3447e762009-08-20 22:52:58 +00001007 // If we have declared a member function template, set the access of the
1008 // templated declaration as well.
1009 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1010 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001011 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001012
Anders Carlsson13a69102011-01-20 04:34:22 +00001013 if (VS.isOverrideSpecified()) {
1014 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1015 if (!MD || !MD->isVirtual()) {
1016 Diag(Member->getLocStart(),
1017 diag::override_keyword_only_allowed_on_virtual_member_functions)
1018 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001019 } else
1020 MD->setIsMarkedOverride(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001021 }
1022 if (VS.isFinalSpecified()) {
1023 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1024 if (!MD || !MD->isVirtual()) {
1025 Diag(Member->getLocStart(),
1026 diag::override_keyword_only_allowed_on_virtual_member_functions)
1027 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001028 } else
1029 MD->setIsMarkedFinal(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001030 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001031
1032 CheckOverrideControl(*this, Member);
1033
Douglas Gregor92751d42008-11-17 22:58:34 +00001034 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001035
Douglas Gregor0c880302009-03-11 23:00:04 +00001036 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001037 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001038 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001039 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001040
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001041 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001042 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001043 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001044 }
John McCall48871652010-08-21 09:40:31 +00001045 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001046}
1047
Douglas Gregor15e77a22009-12-31 09:10:24 +00001048/// \brief Find the direct and/or virtual base specifiers that
1049/// correspond to the given base type, for use in base initialization
1050/// within a constructor.
1051static bool FindBaseInitializer(Sema &SemaRef,
1052 CXXRecordDecl *ClassDecl,
1053 QualType BaseType,
1054 const CXXBaseSpecifier *&DirectBaseSpec,
1055 const CXXBaseSpecifier *&VirtualBaseSpec) {
1056 // First, check for a direct base class.
1057 DirectBaseSpec = 0;
1058 for (CXXRecordDecl::base_class_const_iterator Base
1059 = ClassDecl->bases_begin();
1060 Base != ClassDecl->bases_end(); ++Base) {
1061 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1062 // We found a direct base of this type. That's what we're
1063 // initializing.
1064 DirectBaseSpec = &*Base;
1065 break;
1066 }
1067 }
1068
1069 // Check for a virtual base class.
1070 // FIXME: We might be able to short-circuit this if we know in advance that
1071 // there are no virtual bases.
1072 VirtualBaseSpec = 0;
1073 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1074 // We haven't found a base yet; search the class hierarchy for a
1075 // virtual base class.
1076 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1077 /*DetectVirtual=*/false);
1078 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1079 BaseType, Paths)) {
1080 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1081 Path != Paths.end(); ++Path) {
1082 if (Path->back().Base->isVirtual()) {
1083 VirtualBaseSpec = Path->back().Base;
1084 break;
1085 }
1086 }
1087 }
1088 }
1089
1090 return DirectBaseSpec || VirtualBaseSpec;
1091}
1092
Douglas Gregore8381c02008-11-05 04:29:56 +00001093/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001094MemInitResult
John McCall48871652010-08-21 09:40:31 +00001095Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001096 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001097 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001098 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001099 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001100 SourceLocation IdLoc,
1101 SourceLocation LParenLoc,
1102 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001103 SourceLocation RParenLoc,
1104 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001105 if (!ConstructorD)
1106 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001108 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001109
1110 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001111 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001112 if (!Constructor) {
1113 // The user wrote a constructor initializer on a function that is
1114 // not a C++ constructor. Ignore the error for now, because we may
1115 // have more member initializers coming; we'll diagnose it just
1116 // once in ActOnMemInitializers.
1117 return true;
1118 }
1119
1120 CXXRecordDecl *ClassDecl = Constructor->getParent();
1121
1122 // C++ [class.base.init]p2:
1123 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001124 // constructor's class and, if not found in that scope, are looked
1125 // up in the scope containing the constructor's definition.
1126 // [Note: if the constructor's class contains a member with the
1127 // same name as a direct or virtual base class of the class, a
1128 // mem-initializer-id naming the member or base class and composed
1129 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001130 // mem-initializer-id for the hidden base class may be specified
1131 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001132 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001133 // Look for a member, first.
1134 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001135 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001136 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001137 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001138 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001139
Douglas Gregor44e7df62011-01-04 00:32:56 +00001140 if (Member) {
1141 if (EllipsisLoc.isValid())
1142 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1143 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1144
Francois Pichetd583da02010-12-04 09:14:42 +00001145 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001146 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001147 }
1148
Francois Pichetd583da02010-12-04 09:14:42 +00001149 // Handle anonymous union case.
1150 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001151 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1152 if (EllipsisLoc.isValid())
1153 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1154 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1155
Francois Pichetd583da02010-12-04 09:14:42 +00001156 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1157 NumArgs, IdLoc,
1158 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001159 }
Francois Pichetd583da02010-12-04 09:14:42 +00001160 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001161 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001162 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001163 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001164 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001165
1166 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001167 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001168 } else {
1169 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1170 LookupParsedName(R, S, &SS);
1171
1172 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1173 if (!TyD) {
1174 if (R.isAmbiguous()) return true;
1175
John McCallda6841b2010-04-09 19:01:14 +00001176 // We don't want access-control diagnostics here.
1177 R.suppressDiagnostics();
1178
Douglas Gregora3b624a2010-01-19 06:46:48 +00001179 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1180 bool NotUnknownSpecialization = false;
1181 DeclContext *DC = computeDeclContext(SS, false);
1182 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1183 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1184
1185 if (!NotUnknownSpecialization) {
1186 // When the scope specifier can refer to a member of an unknown
1187 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001188 BaseType = CheckTypenameType(ETK_None,
1189 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001190 *MemberOrBase, SourceLocation(),
1191 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001192 if (BaseType.isNull())
1193 return true;
1194
Douglas Gregora3b624a2010-01-19 06:46:48 +00001195 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001196 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001197 }
1198 }
1199
Douglas Gregor15e77a22009-12-31 09:10:24 +00001200 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001201 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001202 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1203 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001204 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001205 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001206 // We have found a non-static data member with a similar
1207 // name to what was typed; complain and initialize that
1208 // member.
1209 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1210 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001211 << FixItHint::CreateReplacement(R.getNameLoc(),
1212 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001213 Diag(Member->getLocation(), diag::note_previous_decl)
1214 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001215
1216 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1217 LParenLoc, RParenLoc);
1218 }
1219 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1220 const CXXBaseSpecifier *DirectBaseSpec;
1221 const CXXBaseSpecifier *VirtualBaseSpec;
1222 if (FindBaseInitializer(*this, ClassDecl,
1223 Context.getTypeDeclType(Type),
1224 DirectBaseSpec, VirtualBaseSpec)) {
1225 // We have found a direct or virtual base class with a
1226 // similar name to what was typed; complain and initialize
1227 // that base class.
1228 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1229 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001230 << FixItHint::CreateReplacement(R.getNameLoc(),
1231 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001232
1233 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1234 : VirtualBaseSpec;
1235 Diag(BaseSpec->getSourceRange().getBegin(),
1236 diag::note_base_class_specified_here)
1237 << BaseSpec->getType()
1238 << BaseSpec->getSourceRange();
1239
Douglas Gregor15e77a22009-12-31 09:10:24 +00001240 TyD = Type;
1241 }
1242 }
1243 }
1244
Douglas Gregora3b624a2010-01-19 06:46:48 +00001245 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001246 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1247 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1248 return true;
1249 }
John McCallb5a0d312009-12-21 10:41:20 +00001250 }
1251
Douglas Gregora3b624a2010-01-19 06:46:48 +00001252 if (BaseType.isNull()) {
1253 BaseType = Context.getTypeDeclType(TyD);
1254 if (SS.isSet()) {
1255 NestedNameSpecifier *Qualifier =
1256 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001257
Douglas Gregora3b624a2010-01-19 06:46:48 +00001258 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001259 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001260 }
John McCallb5a0d312009-12-21 10:41:20 +00001261 }
1262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263
John McCallbcd03502009-12-07 02:54:59 +00001264 if (!TInfo)
1265 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001266
John McCallbcd03502009-12-07 02:54:59 +00001267 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001268 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001269}
1270
John McCalle22a04a2009-11-04 23:02:40 +00001271/// Checks an initializer expression for use of uninitialized fields, such as
1272/// containing the field that is being initialized. Returns true if there is an
1273/// uninitialized field was used an updates the SourceLocation parameter; false
1274/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001275static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001276 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001277 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001278 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1279
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001280 if (isa<CallExpr>(S)) {
1281 // Do not descend into function calls or constructors, as the use
1282 // of an uninitialized field may be valid. One would have to inspect
1283 // the contents of the function/ctor to determine if it is safe or not.
1284 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1285 // may be safe, depending on what the function/ctor does.
1286 return false;
1287 }
1288 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1289 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001290
1291 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1292 // The member expression points to a static data member.
1293 assert(VD->isStaticDataMember() &&
1294 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001295 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001296 return false;
1297 }
1298
1299 if (isa<EnumConstantDecl>(RhsField)) {
1300 // The member expression points to an enum.
1301 return false;
1302 }
1303
John McCalle22a04a2009-11-04 23:02:40 +00001304 if (RhsField == LhsField) {
1305 // Initializing a field with itself. Throw a warning.
1306 // But wait; there are exceptions!
1307 // Exception #1: The field may not belong to this record.
1308 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001309 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001310 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1311 // Even though the field matches, it does not belong to this record.
1312 return false;
1313 }
1314 // None of the exceptions triggered; return true to indicate an
1315 // uninitialized field was used.
1316 *L = ME->getMemberLoc();
1317 return true;
1318 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001319 } else if (isa<SizeOfAlignOfExpr>(S)) {
1320 // sizeof/alignof doesn't reference contents, do not warn.
1321 return false;
1322 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1323 // address-of doesn't reference contents (the pointer may be dereferenced
1324 // in the same expression but it would be rare; and weird).
1325 if (UOE->getOpcode() == UO_AddrOf)
1326 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001327 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001328 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1329 it != e; ++it) {
1330 if (!*it) {
1331 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001332 continue;
1333 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001334 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1335 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001336 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001337 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001338}
1339
John McCallfaf5fb42010-08-26 23:41:50 +00001340MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001341Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001342 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001343 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001344 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001345 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1346 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1347 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001348 "Member must be a FieldDecl or IndirectFieldDecl");
1349
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001350 if (Member->isInvalidDecl())
1351 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001352
John McCalle22a04a2009-11-04 23:02:40 +00001353 // Diagnose value-uses of fields to initialize themselves, e.g.
1354 // foo(foo)
1355 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001356 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001357 for (unsigned i = 0; i < NumArgs; ++i) {
1358 SourceLocation L;
1359 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1360 // FIXME: Return true in the case when other fields are used before being
1361 // uninitialized. For example, let this field be the i'th field. When
1362 // initializing the i'th field, throw a warning if any of the >= i'th
1363 // fields are used, as they are not yet initialized.
1364 // Right now we are only handling the case where the i'th field uses
1365 // itself in its initializer.
1366 Diag(L, diag::warn_field_is_uninit);
1367 }
1368 }
1369
Eli Friedman8e1433b2009-07-29 19:44:27 +00001370 bool HasDependentArg = false;
1371 for (unsigned i = 0; i < NumArgs; i++)
1372 HasDependentArg |= Args[i]->isTypeDependent();
1373
Chandler Carruthd44c3102010-12-06 09:23:57 +00001374 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001375 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001376 // Can't check initialization for a member of dependent type or when
1377 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001378 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1379 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001380
1381 // Erase any temporaries within this evaluation context; we're not
1382 // going to track them in the AST, since we'll be rebuilding the
1383 // ASTs during template instantiation.
1384 ExprTemporaries.erase(
1385 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1386 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001387 } else {
1388 // Initialize the member.
1389 InitializedEntity MemberEntity =
1390 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1391 : InitializedEntity::InitializeMember(IndirectMember, 0);
1392 InitializationKind Kind =
1393 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001394
Chandler Carruthd44c3102010-12-06 09:23:57 +00001395 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1396
1397 ExprResult MemberInit =
1398 InitSeq.Perform(*this, MemberEntity, Kind,
1399 MultiExprArg(*this, Args, NumArgs), 0);
1400 if (MemberInit.isInvalid())
1401 return true;
1402
1403 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1404
1405 // C++0x [class.base.init]p7:
1406 // The initialization of each base and member constitutes a
1407 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001408 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001409 if (MemberInit.isInvalid())
1410 return true;
1411
1412 // If we are in a dependent context, template instantiation will
1413 // perform this type-checking again. Just save the arguments that we
1414 // received in a ParenListExpr.
1415 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1416 // of the information that we have about the member
1417 // initializer. However, deconstructing the ASTs is a dicey process,
1418 // and this approach is far more likely to get the corner cases right.
1419 if (CurContext->isDependentContext())
1420 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1421 RParenLoc);
1422 else
1423 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001424 }
1425
Chandler Carruthd44c3102010-12-06 09:23:57 +00001426 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001427 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001428 IdLoc, LParenLoc, Init,
1429 RParenLoc);
1430 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001431 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001432 IdLoc, LParenLoc, Init,
1433 RParenLoc);
1434 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001435}
1436
John McCallfaf5fb42010-08-26 23:41:50 +00001437MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001438Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1439 Expr **Args, unsigned NumArgs,
1440 SourceLocation LParenLoc,
1441 SourceLocation RParenLoc,
1442 CXXRecordDecl *ClassDecl,
1443 SourceLocation EllipsisLoc) {
1444 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1445 if (!LangOpts.CPlusPlus0x)
1446 return Diag(Loc, diag::err_delegation_0x_only)
1447 << TInfo->getTypeLoc().getLocalSourceRange();
1448
1449 return Diag(Loc, diag::err_delegation_unimplemented)
1450 << TInfo->getTypeLoc().getLocalSourceRange();
1451}
1452
1453MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001454Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001455 Expr **Args, unsigned NumArgs,
1456 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001457 CXXRecordDecl *ClassDecl,
1458 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001459 bool HasDependentArg = false;
1460 for (unsigned i = 0; i < NumArgs; i++)
1461 HasDependentArg |= Args[i]->isTypeDependent();
1462
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001463 SourceLocation BaseLoc
1464 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1465
1466 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1467 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1468 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1469
1470 // C++ [class.base.init]p2:
1471 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001472 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001473 // of that class, the mem-initializer is ill-formed. A
1474 // mem-initializer-list can initialize a base class using any
1475 // name that denotes that base class type.
1476 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1477
Douglas Gregor44e7df62011-01-04 00:32:56 +00001478 if (EllipsisLoc.isValid()) {
1479 // This is a pack expansion.
1480 if (!BaseType->containsUnexpandedParameterPack()) {
1481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1482 << SourceRange(BaseLoc, RParenLoc);
1483
1484 EllipsisLoc = SourceLocation();
1485 }
1486 } else {
1487 // Check for any unexpanded parameter packs.
1488 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1489 return true;
1490
1491 for (unsigned I = 0; I != NumArgs; ++I)
1492 if (DiagnoseUnexpandedParameterPack(Args[I]))
1493 return true;
1494 }
1495
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001496 // Check for direct and virtual base classes.
1497 const CXXBaseSpecifier *DirectBaseSpec = 0;
1498 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1499 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001500 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1501 BaseType))
1502 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1503 LParenLoc, RParenLoc, ClassDecl,
1504 EllipsisLoc);
1505
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001506 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1507 VirtualBaseSpec);
1508
1509 // C++ [base.class.init]p2:
1510 // Unless the mem-initializer-id names a nonstatic data member of the
1511 // constructor's class or a direct or virtual base of that class, the
1512 // mem-initializer is ill-formed.
1513 if (!DirectBaseSpec && !VirtualBaseSpec) {
1514 // If the class has any dependent bases, then it's possible that
1515 // one of those types will resolve to the same type as
1516 // BaseType. Therefore, just treat this as a dependent base
1517 // class initialization. FIXME: Should we try to check the
1518 // initialization anyway? It seems odd.
1519 if (ClassDecl->hasAnyDependentBases())
1520 Dependent = true;
1521 else
1522 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1523 << BaseType << Context.getTypeDeclType(ClassDecl)
1524 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1525 }
1526 }
1527
1528 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001529 // Can't check initialization for a base of dependent type or when
1530 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001531 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001532 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1533 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001534
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001535 // Erase any temporaries within this evaluation context; we're not
1536 // going to track them in the AST, since we'll be rebuilding the
1537 // ASTs during template instantiation.
1538 ExprTemporaries.erase(
1539 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1540 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001541
Alexis Hunt1d792652011-01-08 20:30:50 +00001542 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001543 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001544 LParenLoc,
1545 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001546 RParenLoc,
1547 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001548 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001549
1550 // C++ [base.class.init]p2:
1551 // If a mem-initializer-id is ambiguous because it designates both
1552 // a direct non-virtual base class and an inherited virtual base
1553 // class, the mem-initializer is ill-formed.
1554 if (DirectBaseSpec && VirtualBaseSpec)
1555 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001556 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001557
1558 CXXBaseSpecifier *BaseSpec
1559 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1560 if (!BaseSpec)
1561 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1562
1563 // Initialize the base.
1564 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001565 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001566 InitializationKind Kind =
1567 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1568
1569 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1570
John McCalldadc5752010-08-24 06:29:42 +00001571 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001572 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001573 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001574 if (BaseInit.isInvalid())
1575 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001576
1577 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001578
1579 // C++0x [class.base.init]p7:
1580 // The initialization of each base and member constitutes a
1581 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001582 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001583 if (BaseInit.isInvalid())
1584 return true;
1585
1586 // If we are in a dependent context, template instantiation will
1587 // perform this type-checking again. Just save the arguments that we
1588 // received in a ParenListExpr.
1589 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1590 // of the information that we have about the base
1591 // initializer. However, deconstructing the ASTs is a dicey process,
1592 // and this approach is far more likely to get the corner cases right.
1593 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001594 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001595 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1596 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001597 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001598 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001599 LParenLoc,
1600 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001601 RParenLoc,
1602 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001603 }
1604
Alexis Hunt1d792652011-01-08 20:30:50 +00001605 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001606 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001607 LParenLoc,
1608 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001609 RParenLoc,
1610 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001611}
1612
Anders Carlsson1b00e242010-04-23 03:10:23 +00001613/// ImplicitInitializerKind - How an implicit base or member initializer should
1614/// initialize its base or member.
1615enum ImplicitInitializerKind {
1616 IIK_Default,
1617 IIK_Copy,
1618 IIK_Move
1619};
1620
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001621static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001622BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001623 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001624 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001625 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001626 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001627 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001628 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1629 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001630
John McCalldadc5752010-08-24 06:29:42 +00001631 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001632
1633 switch (ImplicitInitKind) {
1634 case IIK_Default: {
1635 InitializationKind InitKind
1636 = InitializationKind::CreateDefault(Constructor->getLocation());
1637 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1638 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001639 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001640 break;
1641 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001642
Anders Carlsson1b00e242010-04-23 03:10:23 +00001643 case IIK_Copy: {
1644 ParmVarDecl *Param = Constructor->getParamDecl(0);
1645 QualType ParamType = Param->getType().getNonReferenceType();
1646
1647 Expr *CopyCtorArg =
1648 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001649 Constructor->getLocation(), ParamType,
1650 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001651
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001652 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001653 QualType ArgTy =
1654 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1655 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001656
1657 CXXCastPath BasePath;
1658 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001659 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001660 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001661 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001662
Anders Carlsson1b00e242010-04-23 03:10:23 +00001663 InitializationKind InitKind
1664 = InitializationKind::CreateDirect(Constructor->getLocation(),
1665 SourceLocation(), SourceLocation());
1666 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1667 &CopyCtorArg, 1);
1668 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001669 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001670 break;
1671 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001672
Anders Carlsson1b00e242010-04-23 03:10:23 +00001673 case IIK_Move:
1674 assert(false && "Unhandled initializer kind!");
1675 }
John McCallb268a282010-08-23 23:25:46 +00001676
Douglas Gregora40433a2010-12-07 00:41:46 +00001677 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001678 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001679 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001680
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001681 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001682 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001683 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1684 SourceLocation()),
1685 BaseSpec->isVirtual(),
1686 SourceLocation(),
1687 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001688 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001689 SourceLocation());
1690
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001691 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001692}
1693
Anders Carlsson3c1db572010-04-23 02:15:47 +00001694static bool
1695BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001696 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001697 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001698 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001699 if (Field->isInvalidDecl())
1700 return true;
1701
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001702 SourceLocation Loc = Constructor->getLocation();
1703
Anders Carlsson423f5d82010-04-23 16:04:08 +00001704 if (ImplicitInitKind == IIK_Copy) {
1705 ParmVarDecl *Param = Constructor->getParamDecl(0);
1706 QualType ParamType = Param->getType().getNonReferenceType();
1707
1708 Expr *MemberExprBase =
1709 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001710 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001711
1712 // Build a reference to this field within the parameter.
1713 CXXScopeSpec SS;
1714 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1715 Sema::LookupMemberName);
1716 MemberLookup.addDecl(Field, AS_public);
1717 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001718 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001719 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001720 ParamType, Loc,
1721 /*IsArrow=*/false,
1722 SS,
1723 /*FirstQualifierInScope=*/0,
1724 MemberLookup,
1725 /*TemplateArgs=*/0);
1726 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001727 return true;
1728
Douglas Gregor94f9a482010-05-05 05:51:00 +00001729 // When the field we are copying is an array, create index variables for
1730 // each dimension of the array. We use these index variables to subscript
1731 // the source array, and other clients (e.g., CodeGen) will perform the
1732 // necessary iteration with these index variables.
1733 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1734 QualType BaseType = Field->getType();
1735 QualType SizeType = SemaRef.Context.getSizeType();
1736 while (const ConstantArrayType *Array
1737 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1738 // Create the iteration variable for this array index.
1739 IdentifierInfo *IterationVarName = 0;
1740 {
1741 llvm::SmallString<8> Str;
1742 llvm::raw_svector_ostream OS(Str);
1743 OS << "__i" << IndexVariables.size();
1744 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1745 }
1746 VarDecl *IterationVar
1747 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1748 IterationVarName, SizeType,
1749 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001750 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001751 IndexVariables.push_back(IterationVar);
1752
1753 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001754 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001755 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001756 assert(!IterationVarRef.isInvalid() &&
1757 "Reference to invented variable cannot fail!");
1758
1759 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001760 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001761 Loc,
John McCallb268a282010-08-23 23:25:46 +00001762 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001763 Loc);
1764 if (CopyCtorArg.isInvalid())
1765 return true;
1766
1767 BaseType = Array->getElementType();
1768 }
1769
1770 // Construct the entity that we will be initializing. For an array, this
1771 // will be first element in the array, which may require several levels
1772 // of array-subscript entities.
1773 llvm::SmallVector<InitializedEntity, 4> Entities;
1774 Entities.reserve(1 + IndexVariables.size());
1775 Entities.push_back(InitializedEntity::InitializeMember(Field));
1776 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1777 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1778 0,
1779 Entities.back()));
1780
1781 // Direct-initialize to use the copy constructor.
1782 InitializationKind InitKind =
1783 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1784
1785 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1786 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1787 &CopyCtorArgE, 1);
1788
John McCalldadc5752010-08-24 06:29:42 +00001789 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001790 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001791 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001792 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001793 if (MemberInit.isInvalid())
1794 return true;
1795
1796 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001797 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001798 MemberInit.takeAs<Expr>(), Loc,
1799 IndexVariables.data(),
1800 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001801 return false;
1802 }
1803
Anders Carlsson423f5d82010-04-23 16:04:08 +00001804 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1805
Anders Carlsson3c1db572010-04-23 02:15:47 +00001806 QualType FieldBaseElementType =
1807 SemaRef.Context.getBaseElementType(Field->getType());
1808
Anders Carlsson3c1db572010-04-23 02:15:47 +00001809 if (FieldBaseElementType->isRecordType()) {
1810 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001811 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001812 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001813
1814 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001815 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001816 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001817
Douglas Gregora40433a2010-12-07 00:41:46 +00001818 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001819 if (MemberInit.isInvalid())
1820 return true;
1821
1822 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001823 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001824 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001825 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001826 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001827 return false;
1828 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001829
1830 if (FieldBaseElementType->isReferenceType()) {
1831 SemaRef.Diag(Constructor->getLocation(),
1832 diag::err_uninitialized_member_in_ctor)
1833 << (int)Constructor->isImplicit()
1834 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1835 << 0 << Field->getDeclName();
1836 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1837 return true;
1838 }
1839
1840 if (FieldBaseElementType.isConstQualified()) {
1841 SemaRef.Diag(Constructor->getLocation(),
1842 diag::err_uninitialized_member_in_ctor)
1843 << (int)Constructor->isImplicit()
1844 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1845 << 1 << Field->getDeclName();
1846 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1847 return true;
1848 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001849
1850 // Nothing to initialize.
1851 CXXMemberInit = 0;
1852 return false;
1853}
John McCallbc83b3f2010-05-20 23:23:51 +00001854
1855namespace {
1856struct BaseAndFieldInfo {
1857 Sema &S;
1858 CXXConstructorDecl *Ctor;
1859 bool AnyErrorsInInits;
1860 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001861 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1862 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001863
1864 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1865 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1866 // FIXME: Handle implicit move constructors.
1867 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1868 IIK = IIK_Copy;
1869 else
1870 IIK = IIK_Default;
1871 }
1872};
1873}
1874
1875static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1876 FieldDecl *Top, FieldDecl *Field) {
1877
Chandler Carruth139e9622010-06-30 02:59:29 +00001878 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001879 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001880 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001881 return false;
1882 }
1883
1884 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1885 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1886 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001887 CXXRecordDecl *FieldClassDecl
1888 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001889
1890 // Even though union members never have non-trivial default
1891 // constructions in C++03, we still build member initializers for aggregate
1892 // record types which can be union members, and C++0x allows non-trivial
1893 // default constructors for union members, so we ensure that only one
1894 // member is initialized for these.
1895 if (FieldClassDecl->isUnion()) {
1896 // First check for an explicit initializer for one field.
1897 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1898 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001899 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001900 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001901
1902 // Once we've initialized a field of an anonymous union, the union
1903 // field in the class is also initialized, so exit immediately.
1904 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001905 } else if ((*FA)->isAnonymousStructOrUnion()) {
1906 if (CollectFieldInitializer(Info, Top, *FA))
1907 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001908 }
1909 }
1910
1911 // Fallthrough and construct a default initializer for the union as
1912 // a whole, which can call its default constructor if such a thing exists
1913 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1914 // behavior going forward with C++0x, when anonymous unions there are
1915 // finalized, we should revisit this.
1916 } else {
1917 // For structs, we simply descend through to initialize all members where
1918 // necessary.
1919 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1920 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1921 if (CollectFieldInitializer(Info, Top, *FA))
1922 return true;
1923 }
1924 }
John McCallbc83b3f2010-05-20 23:23:51 +00001925 }
1926
1927 // Don't try to build an implicit initializer if there were semantic
1928 // errors in any of the initializers (and therefore we might be
1929 // missing some that the user actually wrote).
1930 if (Info.AnyErrorsInInits)
1931 return false;
1932
Alexis Hunt1d792652011-01-08 20:30:50 +00001933 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001934 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1935 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001936
Francois Pichetd583da02010-12-04 09:14:42 +00001937 if (Init)
1938 Info.AllToInit.push_back(Init);
1939
John McCallbc83b3f2010-05-20 23:23:51 +00001940 return false;
1941}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001942
Eli Friedman9cf6b592009-11-09 19:20:36 +00001943bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001944Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1945 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001946 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001947 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001948 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001949 // Just store the initializers as written, they will be checked during
1950 // instantiation.
1951 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001952 Constructor->setNumCtorInitializers(NumInitializers);
1953 CXXCtorInitializer **baseOrMemberInitializers =
1954 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001955 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001956 NumInitializers * sizeof(CXXCtorInitializer*));
1957 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001958 }
1959
1960 return false;
1961 }
1962
John McCallbc83b3f2010-05-20 23:23:51 +00001963 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001964
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001965 // We need to build the initializer AST according to order of construction
1966 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001967 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001968 if (!ClassDecl)
1969 return true;
1970
Eli Friedman9cf6b592009-11-09 19:20:36 +00001971 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001972
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001973 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001974 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001975
1976 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001977 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001978 else
Francois Pichetd583da02010-12-04 09:14:42 +00001979 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001980 }
1981
Anders Carlsson43c64af2010-04-21 19:52:01 +00001982 // Keep track of the direct virtual bases.
1983 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1984 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1985 E = ClassDecl->bases_end(); I != E; ++I) {
1986 if (I->isVirtual())
1987 DirectVBases.insert(I);
1988 }
1989
Anders Carlssondb0a9652010-04-02 06:26:44 +00001990 // Push virtual bases before others.
1991 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1992 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1993
Alexis Hunt1d792652011-01-08 20:30:50 +00001994 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001995 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1996 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001997 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001998 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00001999 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002000 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002001 VBase, IsInheritedVirtualBase,
2002 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002003 HadError = true;
2004 continue;
2005 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002006
John McCallbc83b3f2010-05-20 23:23:51 +00002007 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002008 }
2009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
John McCallbc83b3f2010-05-20 23:23:51 +00002011 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002012 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2013 E = ClassDecl->bases_end(); Base != E; ++Base) {
2014 // Virtuals are in the virtual base list and already constructed.
2015 if (Base->isVirtual())
2016 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Alexis Hunt1d792652011-01-08 20:30:50 +00002018 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002019 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2020 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002021 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002022 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002023 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002024 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002025 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002026 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002027 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002028 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002029
John McCallbc83b3f2010-05-20 23:23:51 +00002030 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002031 }
2032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCallbc83b3f2010-05-20 23:23:51 +00002034 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002035 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002036 E = ClassDecl->field_end(); Field != E; ++Field) {
2037 if ((*Field)->getType()->isIncompleteArrayType()) {
2038 assert(ClassDecl->hasFlexibleArrayMember() &&
2039 "Incomplete array type is not valid");
2040 continue;
2041 }
John McCallbc83b3f2010-05-20 23:23:51 +00002042 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002043 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002044 }
Mike Stump11289f42009-09-09 15:08:12 +00002045
John McCallbc83b3f2010-05-20 23:23:51 +00002046 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002047 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002048 Constructor->setNumCtorInitializers(NumInitializers);
2049 CXXCtorInitializer **baseOrMemberInitializers =
2050 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002051 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002052 NumInitializers * sizeof(CXXCtorInitializer*));
2053 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002054
John McCalla6309952010-03-16 21:39:52 +00002055 // Constructors implicitly reference the base and member
2056 // destructors.
2057 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2058 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002059 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002060
2061 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002062}
2063
Eli Friedman952c15d2009-07-21 19:28:10 +00002064static void *GetKeyForTopLevelField(FieldDecl *Field) {
2065 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002066 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002067 if (RT->getDecl()->isAnonymousStructOrUnion())
2068 return static_cast<void *>(RT->getDecl());
2069 }
2070 return static_cast<void *>(Field);
2071}
2072
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002073static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002074 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002075}
2076
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002077static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002078 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002079 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002080 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002081
Eli Friedman952c15d2009-07-21 19:28:10 +00002082 // For fields injected into the class via declaration of an anonymous union,
2083 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002084 FieldDecl *Field = Member->getAnyMember();
2085
John McCall23eebd92010-04-10 09:28:51 +00002086 // If the field is a member of an anonymous struct or union, our key
2087 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002088 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002089 if (RD->isAnonymousStructOrUnion()) {
2090 while (true) {
2091 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2092 if (Parent->isAnonymousStructOrUnion())
2093 RD = Parent;
2094 else
2095 break;
2096 }
2097
Anders Carlsson83ac3122010-03-30 16:19:37 +00002098 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002099 }
Mike Stump11289f42009-09-09 15:08:12 +00002100
Anders Carlssona942dcd2010-03-30 15:39:27 +00002101 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002102}
2103
Anders Carlssone857b292010-04-02 03:37:03 +00002104static void
2105DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002106 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002107 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002108 unsigned NumInits) {
2109 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002110 return;
Mike Stump11289f42009-09-09 15:08:12 +00002111
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002112 // Don't check initializers order unless the warning is enabled at the
2113 // location of at least one initializer.
2114 bool ShouldCheckOrder = false;
2115 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002116 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002117 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2118 Init->getSourceLocation())
2119 != Diagnostic::Ignored) {
2120 ShouldCheckOrder = true;
2121 break;
2122 }
2123 }
2124 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002125 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002126
John McCallbb7b6582010-04-10 07:37:23 +00002127 // Build the list of bases and members in the order that they'll
2128 // actually be initialized. The explicit initializers should be in
2129 // this same order but may be missing things.
2130 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002131
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002132 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2133
John McCallbb7b6582010-04-10 07:37:23 +00002134 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002135 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002136 ClassDecl->vbases_begin(),
2137 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002138 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002139
John McCallbb7b6582010-04-10 07:37:23 +00002140 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002141 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002142 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002143 if (Base->isVirtual())
2144 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002145 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002146 }
Mike Stump11289f42009-09-09 15:08:12 +00002147
John McCallbb7b6582010-04-10 07:37:23 +00002148 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002149 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2150 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002151 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002152
John McCallbb7b6582010-04-10 07:37:23 +00002153 unsigned NumIdealInits = IdealInitKeys.size();
2154 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002155
Alexis Hunt1d792652011-01-08 20:30:50 +00002156 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002157 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002158 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002159 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002160
2161 // Scan forward to try to find this initializer in the idealized
2162 // initializers list.
2163 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2164 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002165 break;
John McCallbb7b6582010-04-10 07:37:23 +00002166
2167 // If we didn't find this initializer, it must be because we
2168 // scanned past it on a previous iteration. That can only
2169 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002170 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002171 Sema::SemaDiagnosticBuilder D =
2172 SemaRef.Diag(PrevInit->getSourceLocation(),
2173 diag::warn_initializer_out_of_order);
2174
Francois Pichetd583da02010-12-04 09:14:42 +00002175 if (PrevInit->isAnyMemberInitializer())
2176 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002177 else
2178 D << 1 << PrevInit->getBaseClassInfo()->getType();
2179
Francois Pichetd583da02010-12-04 09:14:42 +00002180 if (Init->isAnyMemberInitializer())
2181 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002182 else
2183 D << 1 << Init->getBaseClassInfo()->getType();
2184
2185 // Move back to the initializer's location in the ideal list.
2186 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2187 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002188 break;
John McCallbb7b6582010-04-10 07:37:23 +00002189
2190 assert(IdealIndex != NumIdealInits &&
2191 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002192 }
John McCallbb7b6582010-04-10 07:37:23 +00002193
2194 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002195 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002196}
2197
John McCall23eebd92010-04-10 09:28:51 +00002198namespace {
2199bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002200 CXXCtorInitializer *Init,
2201 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002202 if (!PrevInit) {
2203 PrevInit = Init;
2204 return false;
2205 }
2206
2207 if (FieldDecl *Field = Init->getMember())
2208 S.Diag(Init->getSourceLocation(),
2209 diag::err_multiple_mem_initialization)
2210 << Field->getDeclName()
2211 << Init->getSourceRange();
2212 else {
John McCall424cec92011-01-19 06:33:43 +00002213 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002214 assert(BaseClass && "neither field nor base");
2215 S.Diag(Init->getSourceLocation(),
2216 diag::err_multiple_base_initialization)
2217 << QualType(BaseClass, 0)
2218 << Init->getSourceRange();
2219 }
2220 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2221 << 0 << PrevInit->getSourceRange();
2222
2223 return true;
2224}
2225
Alexis Hunt1d792652011-01-08 20:30:50 +00002226typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002227typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2228
2229bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002230 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002231 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002232 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002233 RecordDecl *Parent = Field->getParent();
2234 if (!Parent->isAnonymousStructOrUnion())
2235 return false;
2236
2237 NamedDecl *Child = Field;
2238 do {
2239 if (Parent->isUnion()) {
2240 UnionEntry &En = Unions[Parent];
2241 if (En.first && En.first != Child) {
2242 S.Diag(Init->getSourceLocation(),
2243 diag::err_multiple_mem_union_initialization)
2244 << Field->getDeclName()
2245 << Init->getSourceRange();
2246 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2247 << 0 << En.second->getSourceRange();
2248 return true;
2249 } else if (!En.first) {
2250 En.first = Child;
2251 En.second = Init;
2252 }
2253 }
2254
2255 Child = Parent;
2256 Parent = cast<RecordDecl>(Parent->getDeclContext());
2257 } while (Parent->isAnonymousStructOrUnion());
2258
2259 return false;
2260}
2261}
2262
Anders Carlssone857b292010-04-02 03:37:03 +00002263/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002264void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002265 SourceLocation ColonLoc,
2266 MemInitTy **meminits, unsigned NumMemInits,
2267 bool AnyErrors) {
2268 if (!ConstructorDecl)
2269 return;
2270
2271 AdjustDeclIfTemplate(ConstructorDecl);
2272
2273 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002274 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002275
2276 if (!Constructor) {
2277 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2278 return;
2279 }
2280
Alexis Hunt1d792652011-01-08 20:30:50 +00002281 CXXCtorInitializer **MemInits =
2282 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002283
2284 // Mapping for the duplicate initializers check.
2285 // For member initializers, this is keyed with a FieldDecl*.
2286 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002287 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002288
2289 // Mapping for the inconsistent anonymous-union initializers check.
2290 RedundantUnionMap MemberUnions;
2291
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002292 bool HadError = false;
2293 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002294 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002295
Abramo Bagnara341d7832010-05-26 18:09:23 +00002296 // Set the source order index.
2297 Init->setSourceOrder(i);
2298
Francois Pichetd583da02010-12-04 09:14:42 +00002299 if (Init->isAnyMemberInitializer()) {
2300 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002301 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2302 CheckRedundantUnionInit(*this, Init, MemberUnions))
2303 HadError = true;
2304 } else {
2305 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2306 if (CheckRedundantInit(*this, Init, Members[Key]))
2307 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002308 }
Anders Carlssone857b292010-04-02 03:37:03 +00002309 }
2310
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002311 if (HadError)
2312 return;
2313
Anders Carlssone857b292010-04-02 03:37:03 +00002314 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002315
Alexis Hunt1d792652011-01-08 20:30:50 +00002316 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002317}
2318
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002319void
John McCalla6309952010-03-16 21:39:52 +00002320Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2321 CXXRecordDecl *ClassDecl) {
2322 // Ignore dependent contexts.
2323 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002324 return;
John McCall1064d7e2010-03-16 05:22:47 +00002325
2326 // FIXME: all the access-control diagnostics are positioned on the
2327 // field/base declaration. That's probably good; that said, the
2328 // user might reasonably want to know why the destructor is being
2329 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002330
Anders Carlssondee9a302009-11-17 04:44:12 +00002331 // Non-static data members.
2332 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2333 E = ClassDecl->field_end(); I != E; ++I) {
2334 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002335 if (Field->isInvalidDecl())
2336 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002337 QualType FieldType = Context.getBaseElementType(Field->getType());
2338
2339 const RecordType* RT = FieldType->getAs<RecordType>();
2340 if (!RT)
2341 continue;
2342
2343 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2344 if (FieldClassDecl->hasTrivialDestructor())
2345 continue;
2346
Douglas Gregore71edda2010-07-01 22:47:18 +00002347 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002348 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002349 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002350 << Field->getDeclName()
2351 << FieldType);
2352
John McCalla6309952010-03-16 21:39:52 +00002353 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002354 }
2355
John McCall1064d7e2010-03-16 05:22:47 +00002356 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2357
Anders Carlssondee9a302009-11-17 04:44:12 +00002358 // Bases.
2359 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2360 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002361 // Bases are always records in a well-formed non-dependent class.
2362 const RecordType *RT = Base->getType()->getAs<RecordType>();
2363
2364 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002365 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002366 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002367
2368 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002369 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002370 if (BaseClassDecl->hasTrivialDestructor())
2371 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002372
Douglas Gregore71edda2010-07-01 22:47:18 +00002373 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002374
2375 // FIXME: caret should be on the start of the class name
2376 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002377 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002378 << Base->getType()
2379 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002380
John McCalla6309952010-03-16 21:39:52 +00002381 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002382 }
2383
2384 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002385 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2386 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002387
2388 // Bases are always records in a well-formed non-dependent class.
2389 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2390
2391 // Ignore direct virtual bases.
2392 if (DirectVirtualBases.count(RT))
2393 continue;
2394
Anders Carlssondee9a302009-11-17 04:44:12 +00002395 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002396 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002397 if (BaseClassDecl->hasTrivialDestructor())
2398 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002399
Douglas Gregore71edda2010-07-01 22:47:18 +00002400 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002401 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002402 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002403 << VBase->getType());
2404
John McCalla6309952010-03-16 21:39:52 +00002405 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002406 }
2407}
2408
John McCall48871652010-08-21 09:40:31 +00002409void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002410 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002411 return;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Mike Stump11289f42009-09-09 15:08:12 +00002413 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002414 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002415 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002416}
2417
Mike Stump11289f42009-09-09 15:08:12 +00002418bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002419 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002420 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002421 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002422 else
John McCall02db245d2010-08-18 09:41:07 +00002423 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002424}
2425
Anders Carlssoneabf7702009-08-27 00:13:57 +00002426bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002427 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002428 if (!getLangOptions().CPlusPlus)
2429 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002430
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002431 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002432 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002433
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002434 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002435 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002436 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002437 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002438
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002439 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002440 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002443 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002444 if (!RT)
2445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002446
John McCall67da35c2010-02-04 22:26:26 +00002447 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002448
John McCall02db245d2010-08-18 09:41:07 +00002449 // We can't answer whether something is abstract until it has a
2450 // definition. If it's currently being defined, we'll walk back
2451 // over all the declarations when we have a full definition.
2452 const CXXRecordDecl *Def = RD->getDefinition();
2453 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002454 return false;
2455
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002456 if (!RD->isAbstract())
2457 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002458
Anders Carlssoneabf7702009-08-27 00:13:57 +00002459 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002460 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002461
John McCall02db245d2010-08-18 09:41:07 +00002462 return true;
2463}
2464
2465void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2466 // Check if we've already emitted the list of pure virtual functions
2467 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002468 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002469 return;
Mike Stump11289f42009-09-09 15:08:12 +00002470
Douglas Gregor4165bd62010-03-23 23:47:56 +00002471 CXXFinalOverriderMap FinalOverriders;
2472 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002473
Anders Carlssona2f74f32010-06-03 01:00:02 +00002474 // Keep a set of seen pure methods so we won't diagnose the same method
2475 // more than once.
2476 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2477
Douglas Gregor4165bd62010-03-23 23:47:56 +00002478 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2479 MEnd = FinalOverriders.end();
2480 M != MEnd;
2481 ++M) {
2482 for (OverridingMethods::iterator SO = M->second.begin(),
2483 SOEnd = M->second.end();
2484 SO != SOEnd; ++SO) {
2485 // C++ [class.abstract]p4:
2486 // A class is abstract if it contains or inherits at least one
2487 // pure virtual function for which the final overrider is pure
2488 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002489
Douglas Gregor4165bd62010-03-23 23:47:56 +00002490 //
2491 if (SO->second.size() != 1)
2492 continue;
2493
2494 if (!SO->second.front().Method->isPure())
2495 continue;
2496
Anders Carlssona2f74f32010-06-03 01:00:02 +00002497 if (!SeenPureMethods.insert(SO->second.front().Method))
2498 continue;
2499
Douglas Gregor4165bd62010-03-23 23:47:56 +00002500 Diag(SO->second.front().Method->getLocation(),
2501 diag::note_pure_virtual_function)
2502 << SO->second.front().Method->getDeclName();
2503 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002504 }
2505
2506 if (!PureVirtualClassDiagSet)
2507 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2508 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002509}
2510
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002511namespace {
John McCall02db245d2010-08-18 09:41:07 +00002512struct AbstractUsageInfo {
2513 Sema &S;
2514 CXXRecordDecl *Record;
2515 CanQualType AbstractType;
2516 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002517
John McCall02db245d2010-08-18 09:41:07 +00002518 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2519 : S(S), Record(Record),
2520 AbstractType(S.Context.getCanonicalType(
2521 S.Context.getTypeDeclType(Record))),
2522 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002523
John McCall02db245d2010-08-18 09:41:07 +00002524 void DiagnoseAbstractType() {
2525 if (Invalid) return;
2526 S.DiagnoseAbstractType(Record);
2527 Invalid = true;
2528 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002529
John McCall02db245d2010-08-18 09:41:07 +00002530 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2531};
2532
2533struct CheckAbstractUsage {
2534 AbstractUsageInfo &Info;
2535 const NamedDecl *Ctx;
2536
2537 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2538 : Info(Info), Ctx(Ctx) {}
2539
2540 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2541 switch (TL.getTypeLocClass()) {
2542#define ABSTRACT_TYPELOC(CLASS, PARENT)
2543#define TYPELOC(CLASS, PARENT) \
2544 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2545#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002546 }
John McCall02db245d2010-08-18 09:41:07 +00002547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
John McCall02db245d2010-08-18 09:41:07 +00002549 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2550 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2551 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2552 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2553 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002554 }
John McCall02db245d2010-08-18 09:41:07 +00002555 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002556
John McCall02db245d2010-08-18 09:41:07 +00002557 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2558 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
John McCall02db245d2010-08-18 09:41:07 +00002561 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2562 // Visit the type parameters from a permissive context.
2563 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2564 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2565 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2566 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2567 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2568 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002569 }
John McCall02db245d2010-08-18 09:41:07 +00002570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
John McCall02db245d2010-08-18 09:41:07 +00002572 // Visit pointee types from a permissive context.
2573#define CheckPolymorphic(Type) \
2574 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2575 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2576 }
2577 CheckPolymorphic(PointerTypeLoc)
2578 CheckPolymorphic(ReferenceTypeLoc)
2579 CheckPolymorphic(MemberPointerTypeLoc)
2580 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002581
John McCall02db245d2010-08-18 09:41:07 +00002582 /// Handle all the types we haven't given a more specific
2583 /// implementation for above.
2584 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2585 // Every other kind of type that we haven't called out already
2586 // that has an inner type is either (1) sugar or (2) contains that
2587 // inner type in some way as a subobject.
2588 if (TypeLoc Next = TL.getNextTypeLoc())
2589 return Visit(Next, Sel);
2590
2591 // If there's no inner type and we're in a permissive context,
2592 // don't diagnose.
2593 if (Sel == Sema::AbstractNone) return;
2594
2595 // Check whether the type matches the abstract type.
2596 QualType T = TL.getType();
2597 if (T->isArrayType()) {
2598 Sel = Sema::AbstractArrayType;
2599 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002600 }
John McCall02db245d2010-08-18 09:41:07 +00002601 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2602 if (CT != Info.AbstractType) return;
2603
2604 // It matched; do some magic.
2605 if (Sel == Sema::AbstractArrayType) {
2606 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2607 << T << TL.getSourceRange();
2608 } else {
2609 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2610 << Sel << T << TL.getSourceRange();
2611 }
2612 Info.DiagnoseAbstractType();
2613 }
2614};
2615
2616void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2617 Sema::AbstractDiagSelID Sel) {
2618 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2619}
2620
2621}
2622
2623/// Check for invalid uses of an abstract type in a method declaration.
2624static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2625 CXXMethodDecl *MD) {
2626 // No need to do the check on definitions, which require that
2627 // the return/param types be complete.
2628 if (MD->isThisDeclarationADefinition())
2629 return;
2630
2631 // For safety's sake, just ignore it if we don't have type source
2632 // information. This should never happen for non-implicit methods,
2633 // but...
2634 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2635 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2636}
2637
2638/// Check for invalid uses of an abstract type within a class definition.
2639static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2640 CXXRecordDecl *RD) {
2641 for (CXXRecordDecl::decl_iterator
2642 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2643 Decl *D = *I;
2644 if (D->isImplicit()) continue;
2645
2646 // Methods and method templates.
2647 if (isa<CXXMethodDecl>(D)) {
2648 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2649 } else if (isa<FunctionTemplateDecl>(D)) {
2650 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2651 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2652
2653 // Fields and static variables.
2654 } else if (isa<FieldDecl>(D)) {
2655 FieldDecl *FD = cast<FieldDecl>(D);
2656 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2657 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2658 } else if (isa<VarDecl>(D)) {
2659 VarDecl *VD = cast<VarDecl>(D);
2660 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2661 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2662
2663 // Nested classes and class templates.
2664 } else if (isa<CXXRecordDecl>(D)) {
2665 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2666 } else if (isa<ClassTemplateDecl>(D)) {
2667 CheckAbstractClassUsage(Info,
2668 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2669 }
2670 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002671}
2672
Douglas Gregorc99f1552009-12-03 18:33:45 +00002673/// \brief Perform semantic checks on a class definition that has been
2674/// completing, introducing implicitly-declared members, checking for
2675/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002676void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002677 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002678 return;
2679
John McCall02db245d2010-08-18 09:41:07 +00002680 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2681 AbstractUsageInfo Info(*this, Record);
2682 CheckAbstractClassUsage(Info, Record);
2683 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002684
2685 // If this is not an aggregate type and has no user-declared constructor,
2686 // complain about any non-static data members of reference or const scalar
2687 // type, since they will never get initializers.
2688 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2689 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2690 bool Complained = false;
2691 for (RecordDecl::field_iterator F = Record->field_begin(),
2692 FEnd = Record->field_end();
2693 F != FEnd; ++F) {
2694 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002695 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002696 if (!Complained) {
2697 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2698 << Record->getTagKind() << Record;
2699 Complained = true;
2700 }
2701
2702 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2703 << F->getType()->isReferenceType()
2704 << F->getDeclName();
2705 }
2706 }
2707 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002708
2709 if (Record->isDynamicClass())
2710 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002711
2712 if (Record->getIdentifier()) {
2713 // C++ [class.mem]p13:
2714 // If T is the name of a class, then each of the following shall have a
2715 // name different from T:
2716 // - every member of every anonymous union that is a member of class T.
2717 //
2718 // C++ [class.mem]p14:
2719 // In addition, if class T has a user-declared constructor (12.1), every
2720 // non-static data member of class T shall have a name different from T.
2721 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002722 R.first != R.second; ++R.first) {
2723 NamedDecl *D = *R.first;
2724 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2725 isa<IndirectFieldDecl>(D)) {
2726 Diag(D->getLocation(), diag::err_member_name_of_class)
2727 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002728 break;
2729 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002730 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002731 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002732}
2733
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002734void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002735 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002736 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002737 SourceLocation RBrac,
2738 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002739 if (!TagDecl)
2740 return;
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002742 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002743
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002744 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002745 // strict aliasing violation!
2746 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002747 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002748
Douglas Gregor0be31a22010-07-02 17:43:08 +00002749 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002750 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002751}
2752
Douglas Gregor95755162010-07-01 05:10:53 +00002753namespace {
2754 /// \brief Helper class that collects exception specifications for
2755 /// implicitly-declared special member functions.
2756 class ImplicitExceptionSpecification {
2757 ASTContext &Context;
2758 bool AllowsAllExceptions;
2759 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2760 llvm::SmallVector<QualType, 4> Exceptions;
2761
2762 public:
2763 explicit ImplicitExceptionSpecification(ASTContext &Context)
2764 : Context(Context), AllowsAllExceptions(false) { }
2765
2766 /// \brief Whether the special member function should have any
2767 /// exception specification at all.
2768 bool hasExceptionSpecification() const {
2769 return !AllowsAllExceptions;
2770 }
2771
2772 /// \brief Whether the special member function should have a
2773 /// throw(...) exception specification (a Microsoft extension).
2774 bool hasAnyExceptionSpecification() const {
2775 return false;
2776 }
2777
2778 /// \brief The number of exceptions in the exception specification.
2779 unsigned size() const { return Exceptions.size(); }
2780
2781 /// \brief The set of exceptions in the exception specification.
2782 const QualType *data() const { return Exceptions.data(); }
2783
2784 /// \brief Note that
2785 void CalledDecl(CXXMethodDecl *Method) {
2786 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002787 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002788 return;
2789
2790 const FunctionProtoType *Proto
2791 = Method->getType()->getAs<FunctionProtoType>();
2792
2793 // If this function can throw any exceptions, make a note of that.
2794 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2795 AllowsAllExceptions = true;
2796 ExceptionsSeen.clear();
2797 Exceptions.clear();
2798 return;
2799 }
2800
2801 // Record the exceptions in this function's exception specification.
2802 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2803 EEnd = Proto->exception_end();
2804 E != EEnd; ++E)
2805 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2806 Exceptions.push_back(*E);
2807 }
2808 };
2809}
2810
2811
Douglas Gregor05379422008-11-03 17:51:48 +00002812/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2813/// special functions, such as the default constructor, copy
2814/// constructor, or destructor, to the given C++ class (C++
2815/// [special]p1). This routine can only be executed just before the
2816/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002817void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002818 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002819 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002820
Douglas Gregor54be3392010-07-01 17:57:27 +00002821 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002822 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002823
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002824 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2825 ++ASTContext::NumImplicitCopyAssignmentOperators;
2826
2827 // If we have a dynamic class, then the copy assignment operator may be
2828 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2829 // it shows up in the right place in the vtable and that we diagnose
2830 // problems with the implicit exception specification.
2831 if (ClassDecl->isDynamicClass())
2832 DeclareImplicitCopyAssignment(ClassDecl);
2833 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002834
Douglas Gregor7454c562010-07-02 20:37:36 +00002835 if (!ClassDecl->hasUserDeclaredDestructor()) {
2836 ++ASTContext::NumImplicitDestructors;
2837
2838 // If we have a dynamic class, then the destructor may be virtual, so we
2839 // have to declare the destructor immediately. This ensures that, e.g., it
2840 // shows up in the right place in the vtable and that we diagnose problems
2841 // with the implicit exception specification.
2842 if (ClassDecl->isDynamicClass())
2843 DeclareImplicitDestructor(ClassDecl);
2844 }
Douglas Gregor05379422008-11-03 17:51:48 +00002845}
2846
John McCall48871652010-08-21 09:40:31 +00002847void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002848 if (!D)
2849 return;
2850
2851 TemplateParameterList *Params = 0;
2852 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2853 Params = Template->getTemplateParameters();
2854 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2855 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2856 Params = PartialSpec->getTemplateParameters();
2857 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002858 return;
2859
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002860 for (TemplateParameterList::iterator Param = Params->begin(),
2861 ParamEnd = Params->end();
2862 Param != ParamEnd; ++Param) {
2863 NamedDecl *Named = cast<NamedDecl>(*Param);
2864 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002865 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002866 IdResolver.AddDecl(Named);
2867 }
2868 }
2869}
2870
John McCall48871652010-08-21 09:40:31 +00002871void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002872 if (!RecordD) return;
2873 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002874 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002875 PushDeclContext(S, Record);
2876}
2877
John McCall48871652010-08-21 09:40:31 +00002878void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002879 if (!RecordD) return;
2880 PopDeclContext();
2881}
2882
Douglas Gregor4d87df52008-12-16 21:30:33 +00002883/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2884/// parsing a top-level (non-nested) C++ class, and we are now
2885/// parsing those parts of the given Method declaration that could
2886/// not be parsed earlier (C++ [class.mem]p2), such as default
2887/// arguments. This action should enter the scope of the given
2888/// Method declaration as if we had just parsed the qualified method
2889/// name. However, it should not bring the parameters into scope;
2890/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002891void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002892}
2893
2894/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2895/// C++ method declaration. We're (re-)introducing the given
2896/// function parameter into scope for use in parsing later parts of
2897/// the method declaration. For example, we could see an
2898/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002899void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002900 if (!ParamD)
2901 return;
Mike Stump11289f42009-09-09 15:08:12 +00002902
John McCall48871652010-08-21 09:40:31 +00002903 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002904
2905 // If this parameter has an unparsed default argument, clear it out
2906 // to make way for the parsed default argument.
2907 if (Param->hasUnparsedDefaultArg())
2908 Param->setDefaultArg(0);
2909
John McCall48871652010-08-21 09:40:31 +00002910 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002911 if (Param->getDeclName())
2912 IdResolver.AddDecl(Param);
2913}
2914
2915/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2916/// processing the delayed method declaration for Method. The method
2917/// declaration is now considered finished. There may be a separate
2918/// ActOnStartOfFunctionDef action later (not necessarily
2919/// immediately!) for this method, if it was also defined inside the
2920/// class body.
John McCall48871652010-08-21 09:40:31 +00002921void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002922 if (!MethodD)
2923 return;
Mike Stump11289f42009-09-09 15:08:12 +00002924
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002925 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002926
John McCall48871652010-08-21 09:40:31 +00002927 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002928
2929 // Now that we have our default arguments, check the constructor
2930 // again. It could produce additional diagnostics or affect whether
2931 // the class has implicitly-declared destructors, among other
2932 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002933 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2934 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002935
2936 // Check the default arguments, which we may have added.
2937 if (!Method->isInvalidDecl())
2938 CheckCXXDefaultArguments(Method);
2939}
2940
Douglas Gregor831c93f2008-11-05 20:51:48 +00002941/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002942/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002943/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002944/// emit diagnostics and set the invalid bit to true. In any case, the type
2945/// will be updated to reflect a well-formed type for the constructor and
2946/// returned.
2947QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002948 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002949 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002950
2951 // C++ [class.ctor]p3:
2952 // A constructor shall not be virtual (10.3) or static (9.4). A
2953 // constructor can be invoked for a const, volatile or const
2954 // volatile object. A constructor shall not be declared const,
2955 // volatile, or const volatile (9.3.2).
2956 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002957 if (!D.isInvalidType())
2958 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2959 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2960 << SourceRange(D.getIdentifierLoc());
2961 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002962 }
John McCall8e7d6562010-08-26 03:08:43 +00002963 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002964 if (!D.isInvalidType())
2965 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2966 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2967 << SourceRange(D.getIdentifierLoc());
2968 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002969 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002970 }
Mike Stump11289f42009-09-09 15:08:12 +00002971
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002972 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002973 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002974 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002975 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2976 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002977 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002978 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2979 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002980 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002981 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2982 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002983 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002984 }
Mike Stump11289f42009-09-09 15:08:12 +00002985
Douglas Gregor831c93f2008-11-05 20:51:48 +00002986 // Rebuild the function type "R" without any type qualifiers (in
2987 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002988 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002989 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002990 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2991 return R;
2992
2993 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2994 EPI.TypeQuals = 0;
2995
Chris Lattner38378bf2009-04-25 08:28:21 +00002996 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002997 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002998}
2999
Douglas Gregor4d87df52008-12-16 21:30:33 +00003000/// CheckConstructor - Checks a fully-formed constructor for
3001/// well-formedness, issuing any diagnostics required. Returns true if
3002/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003003void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003004 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003005 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3006 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003007 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003008
3009 // C++ [class.copy]p3:
3010 // A declaration of a constructor for a class X is ill-formed if
3011 // its first parameter is of type (optionally cv-qualified) X and
3012 // either there are no other parameters or else all other
3013 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003014 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003015 ((Constructor->getNumParams() == 1) ||
3016 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003017 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3018 Constructor->getTemplateSpecializationKind()
3019 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003020 QualType ParamType = Constructor->getParamDecl(0)->getType();
3021 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3022 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003023 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003024 const char *ConstRef
3025 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3026 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003027 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003028 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003029
3030 // FIXME: Rather that making the constructor invalid, we should endeavor
3031 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003032 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003033 }
3034 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003035}
3036
John McCalldeb646e2010-08-04 01:04:25 +00003037/// CheckDestructor - Checks a fully-formed destructor definition for
3038/// well-formedness, issuing any diagnostics required. Returns true
3039/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003040bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003041 CXXRecordDecl *RD = Destructor->getParent();
3042
3043 if (Destructor->isVirtual()) {
3044 SourceLocation Loc;
3045
3046 if (!Destructor->isImplicit())
3047 Loc = Destructor->getLocation();
3048 else
3049 Loc = RD->getLocation();
3050
3051 // If we have a virtual destructor, look up the deallocation function
3052 FunctionDecl *OperatorDelete = 0;
3053 DeclarationName Name =
3054 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003055 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003056 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003057
3058 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003059
3060 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003061 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003062
3063 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003064}
3065
Mike Stump11289f42009-09-09 15:08:12 +00003066static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003067FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3068 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3069 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003070 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003071}
3072
Douglas Gregor831c93f2008-11-05 20:51:48 +00003073/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3074/// the well-formednes of the destructor declarator @p D with type @p
3075/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003076/// emit diagnostics and set the declarator to invalid. Even if this happens,
3077/// will be updated to reflect a well-formed type for the destructor and
3078/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003079QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003080 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003081 // C++ [class.dtor]p1:
3082 // [...] A typedef-name that names a class is a class-name
3083 // (7.1.3); however, a typedef-name that names a class shall not
3084 // be used as the identifier in the declarator for a destructor
3085 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003086 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003087 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003088 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003089 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003090
3091 // C++ [class.dtor]p2:
3092 // A destructor is used to destroy objects of its class type. A
3093 // destructor takes no parameters, and no return type can be
3094 // specified for it (not even void). The address of a destructor
3095 // shall not be taken. A destructor shall not be static. A
3096 // destructor can be invoked for a const, volatile or const
3097 // volatile object. A destructor shall not be declared const,
3098 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003099 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003100 if (!D.isInvalidType())
3101 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3102 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003103 << SourceRange(D.getIdentifierLoc())
3104 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3105
John McCall8e7d6562010-08-26 03:08:43 +00003106 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003107 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003108 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003109 // Destructors don't have return types, but the parser will
3110 // happily parse something like:
3111 //
3112 // class X {
3113 // float ~X();
3114 // };
3115 //
3116 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003117 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3118 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3119 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003120 }
Mike Stump11289f42009-09-09 15:08:12 +00003121
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003122 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003123 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003124 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003125 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3126 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003127 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003128 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3129 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003130 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3132 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003133 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003134 }
3135
3136 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003137 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003138 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3139
3140 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003141 FTI.freeArgs();
3142 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003143 }
3144
Mike Stump11289f42009-09-09 15:08:12 +00003145 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003146 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003147 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003148 D.setInvalidType();
3149 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003150
3151 // Rebuild the function type "R" without any type qualifiers or
3152 // parameters (in case any of the errors above fired) and with
3153 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003154 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003155 if (!D.isInvalidType())
3156 return R;
3157
Douglas Gregor95755162010-07-01 05:10:53 +00003158 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003159 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3160 EPI.Variadic = false;
3161 EPI.TypeQuals = 0;
3162 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003163}
3164
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003165/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3166/// well-formednes of the conversion function declarator @p D with
3167/// type @p R. If there are any errors in the declarator, this routine
3168/// will emit diagnostics and return true. Otherwise, it will return
3169/// false. Either way, the type @p R will be updated to reflect a
3170/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003171void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003172 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173 // C++ [class.conv.fct]p1:
3174 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003175 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003176 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003177 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003178 if (!D.isInvalidType())
3179 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3180 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3181 << SourceRange(D.getIdentifierLoc());
3182 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003183 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003184 }
John McCall212fa2e2010-04-13 00:04:31 +00003185
3186 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3187
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003188 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003189 // Conversion functions don't have return types, but the parser will
3190 // happily parse something like:
3191 //
3192 // class X {
3193 // float operator bool();
3194 // };
3195 //
3196 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003197 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3198 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3199 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003200 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003201 }
3202
John McCall212fa2e2010-04-13 00:04:31 +00003203 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3204
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003205 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003206 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003207 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3208
3209 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003210 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003211 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003212 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003213 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003214 D.setInvalidType();
3215 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003216
John McCall212fa2e2010-04-13 00:04:31 +00003217 // Diagnose "&operator bool()" and other such nonsense. This
3218 // is actually a gcc extension which we don't support.
3219 if (Proto->getResultType() != ConvType) {
3220 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3221 << Proto->getResultType();
3222 D.setInvalidType();
3223 ConvType = Proto->getResultType();
3224 }
3225
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003226 // C++ [class.conv.fct]p4:
3227 // The conversion-type-id shall not represent a function type nor
3228 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003229 if (ConvType->isArrayType()) {
3230 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3231 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003232 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003233 } else if (ConvType->isFunctionType()) {
3234 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3235 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003236 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003237 }
3238
3239 // Rebuild the function type "R" without any parameters (in case any
3240 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003241 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003242 if (D.isInvalidType())
3243 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003244
Douglas Gregor5fb53972009-01-14 15:45:31 +00003245 // C++0x explicit conversion operators.
3246 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003247 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003248 diag::warn_explicit_conversion_functions)
3249 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003250}
3251
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003252/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3253/// the declaration of the given C++ conversion function. This routine
3254/// is responsible for recording the conversion function in the C++
3255/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003256Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003257 assert(Conversion && "Expected to receive a conversion function declaration");
3258
Douglas Gregor4287b372008-12-12 08:25:50 +00003259 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003260
3261 // Make sure we aren't redeclaring the conversion function.
3262 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003263
3264 // C++ [class.conv.fct]p1:
3265 // [...] A conversion function is never used to convert a
3266 // (possibly cv-qualified) object to the (possibly cv-qualified)
3267 // same object type (or a reference to it), to a (possibly
3268 // cv-qualified) base class of that type (or a reference to it),
3269 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003270 // FIXME: Suppress this warning if the conversion function ends up being a
3271 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003272 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003273 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003274 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003275 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003276 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3277 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003278 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003279 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003280 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3281 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003282 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003283 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003284 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003285 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003286 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003287 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003288 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003289 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003290 }
3291
Douglas Gregor457104e2010-09-29 04:25:11 +00003292 if (FunctionTemplateDecl *ConversionTemplate
3293 = Conversion->getDescribedFunctionTemplate())
3294 return ConversionTemplate;
3295
John McCall48871652010-08-21 09:40:31 +00003296 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003297}
3298
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003299//===----------------------------------------------------------------------===//
3300// Namespace Handling
3301//===----------------------------------------------------------------------===//
3302
John McCallb1be5232010-08-26 09:15:37 +00003303
3304
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003305/// ActOnStartNamespaceDef - This is called at the start of a namespace
3306/// definition.
John McCall48871652010-08-21 09:40:31 +00003307Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003308 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003309 SourceLocation IdentLoc,
3310 IdentifierInfo *II,
3311 SourceLocation LBrace,
3312 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003313 // anonymous namespace starts at its left brace
3314 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3315 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003316 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003317 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003318
3319 Scope *DeclRegionScope = NamespcScope->getParent();
3320
Anders Carlssona7bcade2010-02-07 01:09:23 +00003321 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3322
John McCall2faf32c2010-12-10 02:59:44 +00003323 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3324 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003325
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003326 if (II) {
3327 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003328 // The identifier in an original-namespace-definition shall not
3329 // have been previously defined in the declarative region in
3330 // which the original-namespace-definition appears. The
3331 // identifier in an original-namespace-definition is the name of
3332 // the namespace. Subsequently in that declarative region, it is
3333 // treated as an original-namespace-name.
3334 //
3335 // Since namespace names are unique in their scope, and we don't
3336 // look through using directives, just
3337 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3338 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor91f84212008-12-11 16:49:14 +00003340 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3341 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003342 if (Namespc->isInline() != OrigNS->isInline()) {
3343 // inline-ness must match
3344 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3345 << Namespc->isInline();
3346 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3347 Namespc->setInvalidDecl();
3348 // Recover by ignoring the new namespace's inline status.
3349 Namespc->setInline(OrigNS->isInline());
3350 }
3351
Douglas Gregor91f84212008-12-11 16:49:14 +00003352 // Attach this namespace decl to the chain of extended namespace
3353 // definitions.
3354 OrigNS->setNextNamespace(Namespc);
3355 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003356
Mike Stump11289f42009-09-09 15:08:12 +00003357 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003358 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003359 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003360 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003361 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003362 } else if (PrevDecl) {
3363 // This is an invalid name redefinition.
3364 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3365 << Namespc->getDeclName();
3366 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3367 Namespc->setInvalidDecl();
3368 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003369 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003370 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003371 // This is the first "real" definition of the namespace "std", so update
3372 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003373 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003374 // We had already defined a dummy namespace "std". Link this new
3375 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003376 StdNS->setNextNamespace(Namespc);
3377 StdNS->setLocation(IdentLoc);
3378 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003379 }
3380
3381 // Make our StdNamespace cache point at the first real definition of the
3382 // "std" namespace.
3383 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003384 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003385
3386 PushOnScopeChains(Namespc, DeclRegionScope);
3387 } else {
John McCall4fa53422009-10-01 00:25:31 +00003388 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003389 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003390
3391 // Link the anonymous namespace into its parent.
3392 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003393 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003394 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3395 PrevDecl = TU->getAnonymousNamespace();
3396 TU->setAnonymousNamespace(Namespc);
3397 } else {
3398 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3399 PrevDecl = ND->getAnonymousNamespace();
3400 ND->setAnonymousNamespace(Namespc);
3401 }
3402
3403 // Link the anonymous namespace with its previous declaration.
3404 if (PrevDecl) {
3405 assert(PrevDecl->isAnonymousNamespace());
3406 assert(!PrevDecl->getNextNamespace());
3407 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3408 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003409
3410 if (Namespc->isInline() != PrevDecl->isInline()) {
3411 // inline-ness must match
3412 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3413 << Namespc->isInline();
3414 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3415 Namespc->setInvalidDecl();
3416 // Recover by ignoring the new namespace's inline status.
3417 Namespc->setInline(PrevDecl->isInline());
3418 }
John McCall0db42252009-12-16 02:06:49 +00003419 }
John McCall4fa53422009-10-01 00:25:31 +00003420
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003421 CurContext->addDecl(Namespc);
3422
John McCall4fa53422009-10-01 00:25:31 +00003423 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3424 // behaves as if it were replaced by
3425 // namespace unique { /* empty body */ }
3426 // using namespace unique;
3427 // namespace unique { namespace-body }
3428 // where all occurrences of 'unique' in a translation unit are
3429 // replaced by the same identifier and this identifier differs
3430 // from all other identifiers in the entire program.
3431
3432 // We just create the namespace with an empty name and then add an
3433 // implicit using declaration, just like the standard suggests.
3434 //
3435 // CodeGen enforces the "universally unique" aspect by giving all
3436 // declarations semantically contained within an anonymous
3437 // namespace internal linkage.
3438
John McCall0db42252009-12-16 02:06:49 +00003439 if (!PrevDecl) {
3440 UsingDirectiveDecl* UD
3441 = UsingDirectiveDecl::Create(Context, CurContext,
3442 /* 'using' */ LBrace,
3443 /* 'namespace' */ SourceLocation(),
3444 /* qualifier */ SourceRange(),
3445 /* NNS */ NULL,
3446 /* identifier */ SourceLocation(),
3447 Namespc,
3448 /* Ancestor */ CurContext);
3449 UD->setImplicit();
3450 CurContext->addDecl(UD);
3451 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003452 }
3453
3454 // Although we could have an invalid decl (i.e. the namespace name is a
3455 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003456 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3457 // for the namespace has the declarations that showed up in that particular
3458 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003459 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003460 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003461}
3462
Sebastian Redla6602e92009-11-23 15:34:23 +00003463/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3464/// is a namespace alias, returns the namespace it points to.
3465static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3466 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3467 return AD->getNamespace();
3468 return dyn_cast_or_null<NamespaceDecl>(D);
3469}
3470
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003471/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3472/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003473void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003474 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3475 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3476 Namespc->setRBracLoc(RBrace);
3477 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003478 if (Namespc->hasAttr<VisibilityAttr>())
3479 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003480}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003481
John McCall28a0cf72010-08-25 07:42:41 +00003482CXXRecordDecl *Sema::getStdBadAlloc() const {
3483 return cast_or_null<CXXRecordDecl>(
3484 StdBadAlloc.get(Context.getExternalSource()));
3485}
3486
3487NamespaceDecl *Sema::getStdNamespace() const {
3488 return cast_or_null<NamespaceDecl>(
3489 StdNamespace.get(Context.getExternalSource()));
3490}
3491
Douglas Gregorcdf87022010-06-29 17:53:46 +00003492/// \brief Retrieve the special "std" namespace, which may require us to
3493/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003494NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003495 if (!StdNamespace) {
3496 // The "std" namespace has not yet been defined, so build one implicitly.
3497 StdNamespace = NamespaceDecl::Create(Context,
3498 Context.getTranslationUnitDecl(),
3499 SourceLocation(),
3500 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003501 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003502 }
3503
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003504 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003505}
3506
John McCall48871652010-08-21 09:40:31 +00003507Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003508 SourceLocation UsingLoc,
3509 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003510 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003511 SourceLocation IdentLoc,
3512 IdentifierInfo *NamespcName,
3513 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003514 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3515 assert(NamespcName && "Invalid NamespcName.");
3516 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003517
3518 // This can only happen along a recovery path.
3519 while (S->getFlags() & Scope::TemplateParamScope)
3520 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003521 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003522
Douglas Gregor889ceb72009-02-03 19:21:40 +00003523 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003524 NestedNameSpecifier *Qualifier = 0;
3525 if (SS.isSet())
3526 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3527
Douglas Gregor34074322009-01-14 22:20:51 +00003528 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003529 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3530 LookupParsedName(R, S, &SS);
3531 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003532 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003533
Douglas Gregorcdf87022010-06-29 17:53:46 +00003534 if (R.empty()) {
3535 // Allow "using namespace std;" or "using namespace ::std;" even if
3536 // "std" hasn't been defined yet, for GCC compatibility.
3537 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3538 NamespcName->isStr("std")) {
3539 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003540 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003541 R.resolveKind();
3542 }
3543 // Otherwise, attempt typo correction.
3544 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3545 CTC_NoKeywords, 0)) {
3546 if (R.getAsSingle<NamespaceDecl>() ||
3547 R.getAsSingle<NamespaceAliasDecl>()) {
3548 if (DeclContext *DC = computeDeclContext(SS, false))
3549 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3550 << NamespcName << DC << Corrected << SS.getRange()
3551 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3552 else
3553 Diag(IdentLoc, diag::err_using_directive_suggest)
3554 << NamespcName << Corrected
3555 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3556 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3557 << Corrected;
3558
3559 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003560 } else {
3561 R.clear();
3562 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003563 }
3564 }
3565 }
3566
John McCall9f3059a2009-10-09 21:13:30 +00003567 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003568 NamedDecl *Named = R.getFoundDecl();
3569 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3570 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003571 // C++ [namespace.udir]p1:
3572 // A using-directive specifies that the names in the nominated
3573 // namespace can be used in the scope in which the
3574 // using-directive appears after the using-directive. During
3575 // unqualified name lookup (3.4.1), the names appear as if they
3576 // were declared in the nearest enclosing namespace which
3577 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003578 // namespace. [Note: in this context, "contains" means "contains
3579 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003580
3581 // Find enclosing context containing both using-directive and
3582 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003583 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003584 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3585 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3586 CommonAncestor = CommonAncestor->getParent();
3587
Sebastian Redla6602e92009-11-23 15:34:23 +00003588 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003589 SS.getRange(),
3590 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003591 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003592 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003593 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003594 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003595 }
3596
Douglas Gregor889ceb72009-02-03 19:21:40 +00003597 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003598 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003599}
3600
3601void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3602 // If scope has associated entity, then using directive is at namespace
3603 // or translation unit scope. We add UsingDirectiveDecls, into
3604 // it's lookup structure.
3605 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003606 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003607 else
3608 // Otherwise it is block-sope. using-directives will affect lookup
3609 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003610 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003611}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003612
Douglas Gregorfec52632009-06-20 00:51:54 +00003613
John McCall48871652010-08-21 09:40:31 +00003614Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003615 AccessSpecifier AS,
3616 bool HasUsingKeyword,
3617 SourceLocation UsingLoc,
3618 CXXScopeSpec &SS,
3619 UnqualifiedId &Name,
3620 AttributeList *AttrList,
3621 bool IsTypeName,
3622 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003623 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003624
Douglas Gregor220f4272009-11-04 16:30:06 +00003625 switch (Name.getKind()) {
3626 case UnqualifiedId::IK_Identifier:
3627 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003628 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003629 case UnqualifiedId::IK_ConversionFunctionId:
3630 break;
3631
3632 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003633 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003634 // C++0x inherited constructors.
3635 if (getLangOptions().CPlusPlus0x) break;
3636
Douglas Gregor220f4272009-11-04 16:30:06 +00003637 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3638 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003639 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003640
3641 case UnqualifiedId::IK_DestructorName:
3642 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3643 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003644 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003645
3646 case UnqualifiedId::IK_TemplateId:
3647 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3648 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003649 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003650 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003651
3652 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3653 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003654 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003655 return 0;
John McCall3969e302009-12-08 07:46:18 +00003656
John McCalla0097262009-12-11 02:10:03 +00003657 // Warn about using declarations.
3658 // TODO: store that the declaration was written without 'using' and
3659 // talk about access decls instead of using decls in the
3660 // diagnostics.
3661 if (!HasUsingKeyword) {
3662 UsingLoc = Name.getSourceRange().getBegin();
3663
3664 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003665 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003666 }
3667
Douglas Gregorc4356532010-12-16 00:46:58 +00003668 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3669 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3670 return 0;
3671
John McCall3f746822009-11-17 05:59:44 +00003672 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003673 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003674 /* IsInstantiation */ false,
3675 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003676 if (UD)
3677 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003678
John McCall48871652010-08-21 09:40:31 +00003679 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003680}
3681
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003682/// \brief Determine whether a using declaration considers the given
3683/// declarations as "equivalent", e.g., if they are redeclarations of
3684/// the same entity or are both typedefs of the same type.
3685static bool
3686IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3687 bool &SuppressRedeclaration) {
3688 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3689 SuppressRedeclaration = false;
3690 return true;
3691 }
3692
3693 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3694 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3695 SuppressRedeclaration = true;
3696 return Context.hasSameType(TD1->getUnderlyingType(),
3697 TD2->getUnderlyingType());
3698 }
3699
3700 return false;
3701}
3702
3703
John McCall84d87672009-12-10 09:41:52 +00003704/// Determines whether to create a using shadow decl for a particular
3705/// decl, given the set of decls existing prior to this using lookup.
3706bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3707 const LookupResult &Previous) {
3708 // Diagnose finding a decl which is not from a base class of the
3709 // current class. We do this now because there are cases where this
3710 // function will silently decide not to build a shadow decl, which
3711 // will pre-empt further diagnostics.
3712 //
3713 // We don't need to do this in C++0x because we do the check once on
3714 // the qualifier.
3715 //
3716 // FIXME: diagnose the following if we care enough:
3717 // struct A { int foo; };
3718 // struct B : A { using A::foo; };
3719 // template <class T> struct C : A {};
3720 // template <class T> struct D : C<T> { using B::foo; } // <---
3721 // This is invalid (during instantiation) in C++03 because B::foo
3722 // resolves to the using decl in B, which is not a base class of D<T>.
3723 // We can't diagnose it immediately because C<T> is an unknown
3724 // specialization. The UsingShadowDecl in D<T> then points directly
3725 // to A::foo, which will look well-formed when we instantiate.
3726 // The right solution is to not collapse the shadow-decl chain.
3727 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3728 DeclContext *OrigDC = Orig->getDeclContext();
3729
3730 // Handle enums and anonymous structs.
3731 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3732 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3733 while (OrigRec->isAnonymousStructOrUnion())
3734 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3735
3736 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3737 if (OrigDC == CurContext) {
3738 Diag(Using->getLocation(),
3739 diag::err_using_decl_nested_name_specifier_is_current_class)
3740 << Using->getNestedNameRange();
3741 Diag(Orig->getLocation(), diag::note_using_decl_target);
3742 return true;
3743 }
3744
3745 Diag(Using->getNestedNameRange().getBegin(),
3746 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3747 << Using->getTargetNestedNameDecl()
3748 << cast<CXXRecordDecl>(CurContext)
3749 << Using->getNestedNameRange();
3750 Diag(Orig->getLocation(), diag::note_using_decl_target);
3751 return true;
3752 }
3753 }
3754
3755 if (Previous.empty()) return false;
3756
3757 NamedDecl *Target = Orig;
3758 if (isa<UsingShadowDecl>(Target))
3759 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3760
John McCalla17e83e2009-12-11 02:33:26 +00003761 // If the target happens to be one of the previous declarations, we
3762 // don't have a conflict.
3763 //
3764 // FIXME: but we might be increasing its access, in which case we
3765 // should redeclare it.
3766 NamedDecl *NonTag = 0, *Tag = 0;
3767 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3768 I != E; ++I) {
3769 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003770 bool Result;
3771 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3772 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003773
3774 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3775 }
3776
John McCall84d87672009-12-10 09:41:52 +00003777 if (Target->isFunctionOrFunctionTemplate()) {
3778 FunctionDecl *FD;
3779 if (isa<FunctionTemplateDecl>(Target))
3780 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3781 else
3782 FD = cast<FunctionDecl>(Target);
3783
3784 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003785 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003786 case Ovl_Overload:
3787 return false;
3788
3789 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003790 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003791 break;
3792
3793 // We found a decl with the exact signature.
3794 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003795 // If we're in a record, we want to hide the target, so we
3796 // return true (without a diagnostic) to tell the caller not to
3797 // build a shadow decl.
3798 if (CurContext->isRecord())
3799 return true;
3800
3801 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003802 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003803 break;
3804 }
3805
3806 Diag(Target->getLocation(), diag::note_using_decl_target);
3807 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3808 return true;
3809 }
3810
3811 // Target is not a function.
3812
John McCall84d87672009-12-10 09:41:52 +00003813 if (isa<TagDecl>(Target)) {
3814 // No conflict between a tag and a non-tag.
3815 if (!Tag) return false;
3816
John McCalle29c5cd2009-12-10 19:51:03 +00003817 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003818 Diag(Target->getLocation(), diag::note_using_decl_target);
3819 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3820 return true;
3821 }
3822
3823 // No conflict between a tag and a non-tag.
3824 if (!NonTag) return false;
3825
John McCalle29c5cd2009-12-10 19:51:03 +00003826 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003827 Diag(Target->getLocation(), diag::note_using_decl_target);
3828 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3829 return true;
3830}
3831
John McCall3f746822009-11-17 05:59:44 +00003832/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003833UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003834 UsingDecl *UD,
3835 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003836
3837 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003838 NamedDecl *Target = Orig;
3839 if (isa<UsingShadowDecl>(Target)) {
3840 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3841 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003842 }
3843
3844 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003845 = UsingShadowDecl::Create(Context, CurContext,
3846 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003847 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003848
3849 Shadow->setAccess(UD->getAccess());
3850 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3851 Shadow->setInvalidDecl();
3852
John McCall3f746822009-11-17 05:59:44 +00003853 if (S)
John McCall3969e302009-12-08 07:46:18 +00003854 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003855 else
John McCall3969e302009-12-08 07:46:18 +00003856 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003857
John McCall3969e302009-12-08 07:46:18 +00003858
John McCall84d87672009-12-10 09:41:52 +00003859 return Shadow;
3860}
John McCall3969e302009-12-08 07:46:18 +00003861
John McCall84d87672009-12-10 09:41:52 +00003862/// Hides a using shadow declaration. This is required by the current
3863/// using-decl implementation when a resolvable using declaration in a
3864/// class is followed by a declaration which would hide or override
3865/// one or more of the using decl's targets; for example:
3866///
3867/// struct Base { void foo(int); };
3868/// struct Derived : Base {
3869/// using Base::foo;
3870/// void foo(int);
3871/// };
3872///
3873/// The governing language is C++03 [namespace.udecl]p12:
3874///
3875/// When a using-declaration brings names from a base class into a
3876/// derived class scope, member functions in the derived class
3877/// override and/or hide member functions with the same name and
3878/// parameter types in a base class (rather than conflicting).
3879///
3880/// There are two ways to implement this:
3881/// (1) optimistically create shadow decls when they're not hidden
3882/// by existing declarations, or
3883/// (2) don't create any shadow decls (or at least don't make them
3884/// visible) until we've fully parsed/instantiated the class.
3885/// The problem with (1) is that we might have to retroactively remove
3886/// a shadow decl, which requires several O(n) operations because the
3887/// decl structures are (very reasonably) not designed for removal.
3888/// (2) avoids this but is very fiddly and phase-dependent.
3889void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003890 if (Shadow->getDeclName().getNameKind() ==
3891 DeclarationName::CXXConversionFunctionName)
3892 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3893
John McCall84d87672009-12-10 09:41:52 +00003894 // Remove it from the DeclContext...
3895 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003896
John McCall84d87672009-12-10 09:41:52 +00003897 // ...and the scope, if applicable...
3898 if (S) {
John McCall48871652010-08-21 09:40:31 +00003899 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003900 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003901 }
3902
John McCall84d87672009-12-10 09:41:52 +00003903 // ...and the using decl.
3904 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3905
3906 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003907 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003908}
3909
John McCalle61f2ba2009-11-18 02:36:19 +00003910/// Builds a using declaration.
3911///
3912/// \param IsInstantiation - Whether this call arises from an
3913/// instantiation of an unresolved using declaration. We treat
3914/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003915NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3916 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003917 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003918 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003919 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003920 bool IsInstantiation,
3921 bool IsTypeName,
3922 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003923 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003924 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003925 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003926
Anders Carlssonf038fc22009-08-28 05:49:21 +00003927 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003928
Anders Carlsson59140b32009-08-28 03:16:11 +00003929 if (SS.isEmpty()) {
3930 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003931 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003932 }
Mike Stump11289f42009-09-09 15:08:12 +00003933
John McCall84d87672009-12-10 09:41:52 +00003934 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003935 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003936 ForRedeclaration);
3937 Previous.setHideTags(false);
3938 if (S) {
3939 LookupName(Previous, S);
3940
3941 // It is really dumb that we have to do this.
3942 LookupResult::Filter F = Previous.makeFilter();
3943 while (F.hasNext()) {
3944 NamedDecl *D = F.next();
3945 if (!isDeclInScope(D, CurContext, S))
3946 F.erase();
3947 }
3948 F.done();
3949 } else {
3950 assert(IsInstantiation && "no scope in non-instantiation");
3951 assert(CurContext->isRecord() && "scope not record in instantiation");
3952 LookupQualifiedName(Previous, CurContext);
3953 }
3954
Mike Stump11289f42009-09-09 15:08:12 +00003955 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003956 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3957
John McCall84d87672009-12-10 09:41:52 +00003958 // Check for invalid redeclarations.
3959 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3960 return 0;
3961
3962 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003963 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3964 return 0;
3965
John McCall84c16cf2009-11-12 03:15:40 +00003966 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003967 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003968 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003969 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003970 // FIXME: not all declaration name kinds are legal here
3971 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3972 UsingLoc, TypenameLoc,
3973 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003974 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003975 } else {
3976 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003977 UsingLoc, SS.getRange(),
3978 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003979 }
John McCallb96ec562009-12-04 22:46:56 +00003980 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003981 D = UsingDecl::Create(Context, CurContext,
3982 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003983 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003984 }
John McCallb96ec562009-12-04 22:46:56 +00003985 D->setAccess(AS);
3986 CurContext->addDecl(D);
3987
3988 if (!LookupContext) return D;
3989 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003990
John McCall0b66eb32010-05-01 00:40:08 +00003991 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003992 UD->setInvalidDecl();
3993 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003994 }
3995
John McCall3969e302009-12-08 07:46:18 +00003996 // Look up the target name.
3997
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003998 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003999
John McCall3969e302009-12-08 07:46:18 +00004000 // Unlike most lookups, we don't always want to hide tag
4001 // declarations: tag names are visible through the using declaration
4002 // even if hidden by ordinary names, *except* in a dependent context
4003 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004004 if (!IsInstantiation)
4005 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004006
John McCall27b18f82009-11-17 02:14:36 +00004007 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004008
John McCall9f3059a2009-10-09 21:13:30 +00004009 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004010 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004011 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004012 UD->setInvalidDecl();
4013 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004014 }
4015
John McCallb96ec562009-12-04 22:46:56 +00004016 if (R.isAmbiguous()) {
4017 UD->setInvalidDecl();
4018 return UD;
4019 }
Mike Stump11289f42009-09-09 15:08:12 +00004020
John McCalle61f2ba2009-11-18 02:36:19 +00004021 if (IsTypeName) {
4022 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004023 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004024 Diag(IdentLoc, diag::err_using_typename_non_type);
4025 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4026 Diag((*I)->getUnderlyingDecl()->getLocation(),
4027 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004028 UD->setInvalidDecl();
4029 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004030 }
4031 } else {
4032 // If we asked for a non-typename and we got a type, error out,
4033 // but only if this is an instantiation of an unresolved using
4034 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004035 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004036 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4037 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004038 UD->setInvalidDecl();
4039 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004040 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004041 }
4042
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004043 // C++0x N2914 [namespace.udecl]p6:
4044 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004045 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004046 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4047 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004048 UD->setInvalidDecl();
4049 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004050 }
Mike Stump11289f42009-09-09 15:08:12 +00004051
John McCall84d87672009-12-10 09:41:52 +00004052 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4053 if (!CheckUsingShadowDecl(UD, *I, Previous))
4054 BuildUsingShadowDecl(S, UD, *I);
4055 }
John McCall3f746822009-11-17 05:59:44 +00004056
4057 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004058}
4059
John McCall84d87672009-12-10 09:41:52 +00004060/// Checks that the given using declaration is not an invalid
4061/// redeclaration. Note that this is checking only for the using decl
4062/// itself, not for any ill-formedness among the UsingShadowDecls.
4063bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4064 bool isTypeName,
4065 const CXXScopeSpec &SS,
4066 SourceLocation NameLoc,
4067 const LookupResult &Prev) {
4068 // C++03 [namespace.udecl]p8:
4069 // C++0x [namespace.udecl]p10:
4070 // A using-declaration is a declaration and can therefore be used
4071 // repeatedly where (and only where) multiple declarations are
4072 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004073 //
John McCall032092f2010-11-29 18:01:58 +00004074 // That's in non-member contexts.
4075 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004076 return false;
4077
4078 NestedNameSpecifier *Qual
4079 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4080
4081 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4082 NamedDecl *D = *I;
4083
4084 bool DTypename;
4085 NestedNameSpecifier *DQual;
4086 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4087 DTypename = UD->isTypeName();
4088 DQual = UD->getTargetNestedNameDecl();
4089 } else if (UnresolvedUsingValueDecl *UD
4090 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4091 DTypename = false;
4092 DQual = UD->getTargetNestedNameSpecifier();
4093 } else if (UnresolvedUsingTypenameDecl *UD
4094 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4095 DTypename = true;
4096 DQual = UD->getTargetNestedNameSpecifier();
4097 } else continue;
4098
4099 // using decls differ if one says 'typename' and the other doesn't.
4100 // FIXME: non-dependent using decls?
4101 if (isTypeName != DTypename) continue;
4102
4103 // using decls differ if they name different scopes (but note that
4104 // template instantiation can cause this check to trigger when it
4105 // didn't before instantiation).
4106 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4107 Context.getCanonicalNestedNameSpecifier(DQual))
4108 continue;
4109
4110 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004111 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004112 return true;
4113 }
4114
4115 return false;
4116}
4117
John McCall3969e302009-12-08 07:46:18 +00004118
John McCallb96ec562009-12-04 22:46:56 +00004119/// Checks that the given nested-name qualifier used in a using decl
4120/// in the current context is appropriately related to the current
4121/// scope. If an error is found, diagnoses it and returns true.
4122bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4123 const CXXScopeSpec &SS,
4124 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004125 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004126
John McCall3969e302009-12-08 07:46:18 +00004127 if (!CurContext->isRecord()) {
4128 // C++03 [namespace.udecl]p3:
4129 // C++0x [namespace.udecl]p8:
4130 // A using-declaration for a class member shall be a member-declaration.
4131
4132 // If we weren't able to compute a valid scope, it must be a
4133 // dependent class scope.
4134 if (!NamedContext || NamedContext->isRecord()) {
4135 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4136 << SS.getRange();
4137 return true;
4138 }
4139
4140 // Otherwise, everything is known to be fine.
4141 return false;
4142 }
4143
4144 // The current scope is a record.
4145
4146 // If the named context is dependent, we can't decide much.
4147 if (!NamedContext) {
4148 // FIXME: in C++0x, we can diagnose if we can prove that the
4149 // nested-name-specifier does not refer to a base class, which is
4150 // still possible in some cases.
4151
4152 // Otherwise we have to conservatively report that things might be
4153 // okay.
4154 return false;
4155 }
4156
4157 if (!NamedContext->isRecord()) {
4158 // Ideally this would point at the last name in the specifier,
4159 // but we don't have that level of source info.
4160 Diag(SS.getRange().getBegin(),
4161 diag::err_using_decl_nested_name_specifier_is_not_class)
4162 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4163 return true;
4164 }
4165
Douglas Gregor7c842292010-12-21 07:41:49 +00004166 if (!NamedContext->isDependentContext() &&
4167 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4168 return true;
4169
John McCall3969e302009-12-08 07:46:18 +00004170 if (getLangOptions().CPlusPlus0x) {
4171 // C++0x [namespace.udecl]p3:
4172 // In a using-declaration used as a member-declaration, the
4173 // nested-name-specifier shall name a base class of the class
4174 // being defined.
4175
4176 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4177 cast<CXXRecordDecl>(NamedContext))) {
4178 if (CurContext == NamedContext) {
4179 Diag(NameLoc,
4180 diag::err_using_decl_nested_name_specifier_is_current_class)
4181 << SS.getRange();
4182 return true;
4183 }
4184
4185 Diag(SS.getRange().getBegin(),
4186 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4187 << (NestedNameSpecifier*) SS.getScopeRep()
4188 << cast<CXXRecordDecl>(CurContext)
4189 << SS.getRange();
4190 return true;
4191 }
4192
4193 return false;
4194 }
4195
4196 // C++03 [namespace.udecl]p4:
4197 // A using-declaration used as a member-declaration shall refer
4198 // to a member of a base class of the class being defined [etc.].
4199
4200 // Salient point: SS doesn't have to name a base class as long as
4201 // lookup only finds members from base classes. Therefore we can
4202 // diagnose here only if we can prove that that can't happen,
4203 // i.e. if the class hierarchies provably don't intersect.
4204
4205 // TODO: it would be nice if "definitely valid" results were cached
4206 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4207 // need to be repeated.
4208
4209 struct UserData {
4210 llvm::DenseSet<const CXXRecordDecl*> Bases;
4211
4212 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4213 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4214 Data->Bases.insert(Base);
4215 return true;
4216 }
4217
4218 bool hasDependentBases(const CXXRecordDecl *Class) {
4219 return !Class->forallBases(collect, this);
4220 }
4221
4222 /// Returns true if the base is dependent or is one of the
4223 /// accumulated base classes.
4224 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4225 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4226 return !Data->Bases.count(Base);
4227 }
4228
4229 bool mightShareBases(const CXXRecordDecl *Class) {
4230 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4231 }
4232 };
4233
4234 UserData Data;
4235
4236 // Returns false if we find a dependent base.
4237 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4238 return false;
4239
4240 // Returns false if the class has a dependent base or if it or one
4241 // of its bases is present in the base set of the current context.
4242 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4243 return false;
4244
4245 Diag(SS.getRange().getBegin(),
4246 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4247 << (NestedNameSpecifier*) SS.getScopeRep()
4248 << cast<CXXRecordDecl>(CurContext)
4249 << SS.getRange();
4250
4251 return true;
John McCallb96ec562009-12-04 22:46:56 +00004252}
4253
John McCall48871652010-08-21 09:40:31 +00004254Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004255 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004256 SourceLocation AliasLoc,
4257 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004258 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004259 SourceLocation IdentLoc,
4260 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004261
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004262 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004263 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4264 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004265
Anders Carlssondca83c42009-03-28 06:23:46 +00004266 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004267 NamedDecl *PrevDecl
4268 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4269 ForRedeclaration);
4270 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4271 PrevDecl = 0;
4272
4273 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004274 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004275 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004276 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004277 // FIXME: At some point, we'll want to create the (redundant)
4278 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004279 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004280 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004281 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004282 }
Mike Stump11289f42009-09-09 15:08:12 +00004283
Anders Carlssondca83c42009-03-28 06:23:46 +00004284 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4285 diag::err_redefinition_different_kind;
4286 Diag(AliasLoc, DiagID) << Alias;
4287 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004288 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004289 }
4290
John McCall27b18f82009-11-17 02:14:36 +00004291 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004292 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004293
John McCall9f3059a2009-10-09 21:13:30 +00004294 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004295 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4296 CTC_NoKeywords, 0)) {
4297 if (R.getAsSingle<NamespaceDecl>() ||
4298 R.getAsSingle<NamespaceAliasDecl>()) {
4299 if (DeclContext *DC = computeDeclContext(SS, false))
4300 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4301 << Ident << DC << Corrected << SS.getRange()
4302 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4303 else
4304 Diag(IdentLoc, diag::err_using_directive_suggest)
4305 << Ident << Corrected
4306 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4307
4308 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4309 << Corrected;
4310
4311 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004312 } else {
4313 R.clear();
4314 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004315 }
4316 }
4317
4318 if (R.empty()) {
4319 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004320 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004321 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004324 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004325 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4326 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004327 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004328 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004329
John McCalld8d0d432010-02-16 06:53:13 +00004330 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004331 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004332}
4333
Douglas Gregora57478e2010-05-01 15:04:51 +00004334namespace {
4335 /// \brief Scoped object used to handle the state changes required in Sema
4336 /// to implicitly define the body of a C++ member function;
4337 class ImplicitlyDefinedFunctionScope {
4338 Sema &S;
4339 DeclContext *PreviousContext;
4340
4341 public:
4342 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4343 : S(S), PreviousContext(S.CurContext)
4344 {
4345 S.CurContext = Method;
4346 S.PushFunctionScope();
4347 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4348 }
4349
4350 ~ImplicitlyDefinedFunctionScope() {
4351 S.PopExpressionEvaluationContext();
4352 S.PopFunctionOrBlockScope();
4353 S.CurContext = PreviousContext;
4354 }
4355 };
4356}
4357
Sebastian Redlc15c3262010-09-13 22:02:47 +00004358static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4359 CXXRecordDecl *D) {
4360 ASTContext &Context = Self.Context;
4361 QualType ClassType = Context.getTypeDeclType(D);
4362 DeclarationName ConstructorName
4363 = Context.DeclarationNames.getCXXConstructorName(
4364 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4365
4366 DeclContext::lookup_const_iterator Con, ConEnd;
4367 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4368 Con != ConEnd; ++Con) {
4369 // FIXME: In C++0x, a constructor template can be a default constructor.
4370 if (isa<FunctionTemplateDecl>(*Con))
4371 continue;
4372
4373 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4374 if (Constructor->isDefaultConstructor())
4375 return Constructor;
4376 }
4377 return 0;
4378}
4379
Douglas Gregor0be31a22010-07-02 17:43:08 +00004380CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4381 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004382 // C++ [class.ctor]p5:
4383 // A default constructor for a class X is a constructor of class X
4384 // that can be called without an argument. If there is no
4385 // user-declared constructor for class X, a default constructor is
4386 // implicitly declared. An implicitly-declared default constructor
4387 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004388 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4389 "Should not build implicit default constructor!");
4390
Douglas Gregor6d880b12010-07-01 22:31:05 +00004391 // C++ [except.spec]p14:
4392 // An implicitly declared special member function (Clause 12) shall have an
4393 // exception-specification. [...]
4394 ImplicitExceptionSpecification ExceptSpec(Context);
4395
4396 // Direct base-class destructors.
4397 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4398 BEnd = ClassDecl->bases_end();
4399 B != BEnd; ++B) {
4400 if (B->isVirtual()) // Handled below.
4401 continue;
4402
Douglas Gregor9672f922010-07-03 00:47:00 +00004403 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4404 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4405 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4406 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004407 else if (CXXConstructorDecl *Constructor
4408 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004409 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004410 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004411 }
4412
4413 // Virtual base-class destructors.
4414 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4415 BEnd = ClassDecl->vbases_end();
4416 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004417 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4418 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4419 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4420 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4421 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004422 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004423 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004424 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004425 }
4426
4427 // Field destructors.
4428 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4429 FEnd = ClassDecl->field_end();
4430 F != FEnd; ++F) {
4431 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004432 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4433 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4434 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4435 ExceptSpec.CalledDecl(
4436 DeclareImplicitDefaultConstructor(FieldClassDecl));
4437 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004438 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004439 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004440 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004441 }
John McCalldb40c7f2010-12-14 08:05:40 +00004442
4443 FunctionProtoType::ExtProtoInfo EPI;
4444 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4445 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4446 EPI.NumExceptions = ExceptSpec.size();
4447 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004448
4449 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004450 CanQualType ClassType
4451 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4452 DeclarationName Name
4453 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004454 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004455 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004456 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004457 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004458 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004459 /*TInfo=*/0,
4460 /*isExplicit=*/false,
4461 /*isInline=*/true,
4462 /*isImplicitlyDeclared=*/true);
4463 DefaultCon->setAccess(AS_public);
4464 DefaultCon->setImplicit();
4465 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004466
4467 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004468 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4469
Douglas Gregor0be31a22010-07-02 17:43:08 +00004470 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004471 PushOnScopeChains(DefaultCon, S, false);
4472 ClassDecl->addDecl(DefaultCon);
4473
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004474 return DefaultCon;
4475}
4476
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004477void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4478 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004479 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004480 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004481 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004482
Anders Carlsson423f5d82010-04-23 16:04:08 +00004483 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004484 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004485
Douglas Gregora57478e2010-05-01 15:04:51 +00004486 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004487 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004488 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004489 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004490 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004491 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004492 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004493 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004494 }
Douglas Gregor73193272010-09-20 16:48:21 +00004495
4496 SourceLocation Loc = Constructor->getLocation();
4497 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4498
4499 Constructor->setUsed();
4500 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004501}
4502
Douglas Gregor0be31a22010-07-02 17:43:08 +00004503CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004504 // C++ [class.dtor]p2:
4505 // If a class has no user-declared destructor, a destructor is
4506 // declared implicitly. An implicitly-declared destructor is an
4507 // inline public member of its class.
4508
4509 // C++ [except.spec]p14:
4510 // An implicitly declared special member function (Clause 12) shall have
4511 // an exception-specification.
4512 ImplicitExceptionSpecification ExceptSpec(Context);
4513
4514 // Direct base-class destructors.
4515 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4516 BEnd = ClassDecl->bases_end();
4517 B != BEnd; ++B) {
4518 if (B->isVirtual()) // Handled below.
4519 continue;
4520
4521 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4522 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004523 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004524 }
4525
4526 // Virtual base-class destructors.
4527 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4528 BEnd = ClassDecl->vbases_end();
4529 B != BEnd; ++B) {
4530 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4531 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004532 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004533 }
4534
4535 // Field destructors.
4536 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4537 FEnd = ClassDecl->field_end();
4538 F != FEnd; ++F) {
4539 if (const RecordType *RecordTy
4540 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4541 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004542 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004543 }
4544
Douglas Gregor7454c562010-07-02 20:37:36 +00004545 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004546 FunctionProtoType::ExtProtoInfo EPI;
4547 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4548 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4549 EPI.NumExceptions = ExceptSpec.size();
4550 EPI.Exceptions = ExceptSpec.data();
4551 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004552
4553 CanQualType ClassType
4554 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4555 DeclarationName Name
4556 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004557 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004558 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004559 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004560 /*isInline=*/true,
4561 /*isImplicitlyDeclared=*/true);
4562 Destructor->setAccess(AS_public);
4563 Destructor->setImplicit();
4564 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004565
4566 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004567 ++ASTContext::NumImplicitDestructorsDeclared;
4568
4569 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004570 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004571 PushOnScopeChains(Destructor, S, false);
4572 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004573
4574 // This could be uniqued if it ever proves significant.
4575 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4576
4577 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004578
Douglas Gregorf1203042010-07-01 19:09:28 +00004579 return Destructor;
4580}
4581
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004582void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004583 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004584 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004585 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004586 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004587 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004588
Douglas Gregor54818f02010-05-12 16:39:35 +00004589 if (Destructor->isInvalidDecl())
4590 return;
4591
Douglas Gregora57478e2010-05-01 15:04:51 +00004592 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004593
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004594 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004595 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4596 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004597
Douglas Gregor54818f02010-05-12 16:39:35 +00004598 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004599 Diag(CurrentLocation, diag::note_member_synthesized_at)
4600 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4601
4602 Destructor->setInvalidDecl();
4603 return;
4604 }
4605
Douglas Gregor73193272010-09-20 16:48:21 +00004606 SourceLocation Loc = Destructor->getLocation();
4607 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4608
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004609 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004610 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004611}
4612
Douglas Gregorb139cd52010-05-01 20:49:11 +00004613/// \brief Builds a statement that copies the given entity from \p From to
4614/// \c To.
4615///
4616/// This routine is used to copy the members of a class with an
4617/// implicitly-declared copy assignment operator. When the entities being
4618/// copied are arrays, this routine builds for loops to copy them.
4619///
4620/// \param S The Sema object used for type-checking.
4621///
4622/// \param Loc The location where the implicit copy is being generated.
4623///
4624/// \param T The type of the expressions being copied. Both expressions must
4625/// have this type.
4626///
4627/// \param To The expression we are copying to.
4628///
4629/// \param From The expression we are copying from.
4630///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004631/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4632/// Otherwise, it's a non-static member subobject.
4633///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004634/// \param Depth Internal parameter recording the depth of the recursion.
4635///
4636/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004637static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004638BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004639 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004640 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004641 // C++0x [class.copy]p30:
4642 // Each subobject is assigned in the manner appropriate to its type:
4643 //
4644 // - if the subobject is of class type, the copy assignment operator
4645 // for the class is used (as if by explicit qualification; that is,
4646 // ignoring any possible virtual overriding functions in more derived
4647 // classes);
4648 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4650
4651 // Look for operator=.
4652 DeclarationName Name
4653 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4654 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4655 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4656
4657 // Filter out any result that isn't a copy-assignment operator.
4658 LookupResult::Filter F = OpLookup.makeFilter();
4659 while (F.hasNext()) {
4660 NamedDecl *D = F.next();
4661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4662 if (Method->isCopyAssignmentOperator())
4663 continue;
4664
4665 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004666 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004667 F.done();
4668
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004669 // Suppress the protected check (C++ [class.protected]) for each of the
4670 // assignment operators we found. This strange dance is required when
4671 // we're assigning via a base classes's copy-assignment operator. To
4672 // ensure that we're getting the right base class subobject (without
4673 // ambiguities), we need to cast "this" to that subobject type; to
4674 // ensure that we don't go through the virtual call mechanism, we need
4675 // to qualify the operator= name with the base class (see below). However,
4676 // this means that if the base class has a protected copy assignment
4677 // operator, the protected member access check will fail. So, we
4678 // rewrite "protected" access to "public" access in this case, since we
4679 // know by construction that we're calling from a derived class.
4680 if (CopyingBaseSubobject) {
4681 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4682 L != LEnd; ++L) {
4683 if (L.getAccess() == AS_protected)
4684 L.setAccess(AS_public);
4685 }
4686 }
4687
Douglas Gregorb139cd52010-05-01 20:49:11 +00004688 // Create the nested-name-specifier that will be used to qualify the
4689 // reference to operator=; this is required to suppress the virtual
4690 // call mechanism.
4691 CXXScopeSpec SS;
4692 SS.setRange(Loc);
4693 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4694 T.getTypePtr()));
4695
4696 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004697 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004698 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004699 /*FirstQualifierInScope=*/0, OpLookup,
4700 /*TemplateArgs=*/0,
4701 /*SuppressQualifierCheck=*/true);
4702 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004703 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004704
4705 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004706
John McCalldadc5752010-08-24 06:29:42 +00004707 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004708 OpEqualRef.takeAs<Expr>(),
4709 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004710 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004711 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004712
4713 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004714 }
John McCallab8c2732010-03-16 06:11:48 +00004715
Douglas Gregorb139cd52010-05-01 20:49:11 +00004716 // - if the subobject is of scalar type, the built-in assignment
4717 // operator is used.
4718 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4719 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004720 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004721 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004722 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004723
4724 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004725 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004726
4727 // - if the subobject is an array, each element is assigned, in the
4728 // manner appropriate to the element type;
4729
4730 // Construct a loop over the array bounds, e.g.,
4731 //
4732 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4733 //
4734 // that will copy each of the array elements.
4735 QualType SizeType = S.Context.getSizeType();
4736
4737 // Create the iteration variable.
4738 IdentifierInfo *IterationVarName = 0;
4739 {
4740 llvm::SmallString<8> Str;
4741 llvm::raw_svector_ostream OS(Str);
4742 OS << "__i" << Depth;
4743 IterationVarName = &S.Context.Idents.get(OS.str());
4744 }
4745 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4746 IterationVarName, SizeType,
4747 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004748 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004749
4750 // Initialize the iteration variable to zero.
4751 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004752 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004753
4754 // Create a reference to the iteration variable; we'll use this several
4755 // times throughout.
4756 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004757 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004758 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4759
4760 // Create the DeclStmt that holds the iteration variable.
4761 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4762
4763 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004764 llvm::APInt Upper
4765 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004766 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004767 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004768 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4769 BO_NE, S.Context.BoolTy,
4770 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004771
4772 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004773 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004774 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4775 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004776
4777 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004778 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4779 IterationVarRef, Loc));
4780 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4781 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004782
4783 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004784 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4785 To, From, CopyingBaseSubobject,
4786 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004787 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004788 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004789
4790 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004791 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004792 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004793 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004794 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004795}
4796
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004797/// \brief Determine whether the given class has a copy assignment operator
4798/// that accepts a const-qualified argument.
4799static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4800 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4801
4802 if (!Class->hasDeclaredCopyAssignment())
4803 S.DeclareImplicitCopyAssignment(Class);
4804
4805 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4806 DeclarationName OpName
4807 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4808
4809 DeclContext::lookup_const_iterator Op, OpEnd;
4810 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4811 // C++ [class.copy]p9:
4812 // A user-declared copy assignment operator is a non-static non-template
4813 // member function of class X with exactly one parameter of type X, X&,
4814 // const X&, volatile X& or const volatile X&.
4815 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4816 if (!Method)
4817 continue;
4818
4819 if (Method->isStatic())
4820 continue;
4821 if (Method->getPrimaryTemplate())
4822 continue;
4823 const FunctionProtoType *FnType =
4824 Method->getType()->getAs<FunctionProtoType>();
4825 assert(FnType && "Overloaded operator has no prototype.");
4826 // Don't assert on this; an invalid decl might have been left in the AST.
4827 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4828 continue;
4829 bool AcceptsConst = true;
4830 QualType ArgType = FnType->getArgType(0);
4831 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4832 ArgType = Ref->getPointeeType();
4833 // Is it a non-const lvalue reference?
4834 if (!ArgType.isConstQualified())
4835 AcceptsConst = false;
4836 }
4837 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4838 continue;
4839
4840 // We have a single argument of type cv X or cv X&, i.e. we've found the
4841 // copy assignment operator. Return whether it accepts const arguments.
4842 return AcceptsConst;
4843 }
4844 assert(Class->isInvalidDecl() &&
4845 "No copy assignment operator declared in valid code.");
4846 return false;
4847}
4848
Douglas Gregor0be31a22010-07-02 17:43:08 +00004849CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004850 // Note: The following rules are largely analoguous to the copy
4851 // constructor rules. Note that virtual bases are not taken into account
4852 // for determining the argument type of the operator. Note also that
4853 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004854
4855
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004856 // C++ [class.copy]p10:
4857 // If the class definition does not explicitly declare a copy
4858 // assignment operator, one is declared implicitly.
4859 // The implicitly-defined copy assignment operator for a class X
4860 // will have the form
4861 //
4862 // X& X::operator=(const X&)
4863 //
4864 // if
4865 bool HasConstCopyAssignment = true;
4866
4867 // -- each direct base class B of X has a copy assignment operator
4868 // whose parameter is of type const B&, const volatile B& or B,
4869 // and
4870 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4871 BaseEnd = ClassDecl->bases_end();
4872 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4873 assert(!Base->getType()->isDependentType() &&
4874 "Cannot generate implicit members for class with dependent bases.");
4875 const CXXRecordDecl *BaseClassDecl
4876 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004877 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004878 }
4879
4880 // -- for all the nonstatic data members of X that are of a class
4881 // type M (or array thereof), each such class type has a copy
4882 // assignment operator whose parameter is of type const M&,
4883 // const volatile M& or M.
4884 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4885 FieldEnd = ClassDecl->field_end();
4886 HasConstCopyAssignment && Field != FieldEnd;
4887 ++Field) {
4888 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4889 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4890 const CXXRecordDecl *FieldClassDecl
4891 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004892 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004893 }
4894 }
4895
4896 // Otherwise, the implicitly declared copy assignment operator will
4897 // have the form
4898 //
4899 // X& X::operator=(X&)
4900 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4901 QualType RetType = Context.getLValueReferenceType(ArgType);
4902 if (HasConstCopyAssignment)
4903 ArgType = ArgType.withConst();
4904 ArgType = Context.getLValueReferenceType(ArgType);
4905
Douglas Gregor68e11362010-07-01 17:48:08 +00004906 // C++ [except.spec]p14:
4907 // An implicitly declared special member function (Clause 12) shall have an
4908 // exception-specification. [...]
4909 ImplicitExceptionSpecification ExceptSpec(Context);
4910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4911 BaseEnd = ClassDecl->bases_end();
4912 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004913 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004914 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004915
4916 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4917 DeclareImplicitCopyAssignment(BaseClassDecl);
4918
Douglas Gregor68e11362010-07-01 17:48:08 +00004919 if (CXXMethodDecl *CopyAssign
4920 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4921 ExceptSpec.CalledDecl(CopyAssign);
4922 }
4923 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4924 FieldEnd = ClassDecl->field_end();
4925 Field != FieldEnd;
4926 ++Field) {
4927 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4928 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004929 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004930 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004931
4932 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4933 DeclareImplicitCopyAssignment(FieldClassDecl);
4934
Douglas Gregor68e11362010-07-01 17:48:08 +00004935 if (CXXMethodDecl *CopyAssign
4936 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4937 ExceptSpec.CalledDecl(CopyAssign);
4938 }
4939 }
4940
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004941 // An implicitly-declared copy assignment operator is an inline public
4942 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004943 FunctionProtoType::ExtProtoInfo EPI;
4944 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4945 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4946 EPI.NumExceptions = ExceptSpec.size();
4947 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004948 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004949 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004950 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004951 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004952 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004953 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004954 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004955 /*isInline=*/true);
4956 CopyAssignment->setAccess(AS_public);
4957 CopyAssignment->setImplicit();
4958 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004959
4960 // Add the parameter to the operator.
4961 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4962 ClassDecl->getLocation(),
4963 /*Id=*/0,
4964 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004965 SC_None,
4966 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004967 CopyAssignment->setParams(&FromParam, 1);
4968
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004969 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004970 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4971
Douglas Gregor0be31a22010-07-02 17:43:08 +00004972 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004973 PushOnScopeChains(CopyAssignment, S, false);
4974 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004975
4976 AddOverriddenMethods(ClassDecl, CopyAssignment);
4977 return CopyAssignment;
4978}
4979
Douglas Gregorb139cd52010-05-01 20:49:11 +00004980void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4981 CXXMethodDecl *CopyAssignOperator) {
4982 assert((CopyAssignOperator->isImplicit() &&
4983 CopyAssignOperator->isOverloadedOperator() &&
4984 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004985 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004986 "DefineImplicitCopyAssignment called for wrong function");
4987
4988 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4989
4990 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4991 CopyAssignOperator->setInvalidDecl();
4992 return;
4993 }
4994
4995 CopyAssignOperator->setUsed();
4996
4997 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004998 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004999
5000 // C++0x [class.copy]p30:
5001 // The implicitly-defined or explicitly-defaulted copy assignment operator
5002 // for a non-union class X performs memberwise copy assignment of its
5003 // subobjects. The direct base classes of X are assigned first, in the
5004 // order of their declaration in the base-specifier-list, and then the
5005 // immediate non-static data members of X are assigned, in the order in
5006 // which they were declared in the class definition.
5007
5008 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005009 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005010
5011 // The parameter for the "other" object, which we are copying from.
5012 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5013 Qualifiers OtherQuals = Other->getType().getQualifiers();
5014 QualType OtherRefType = Other->getType();
5015 if (const LValueReferenceType *OtherRef
5016 = OtherRefType->getAs<LValueReferenceType>()) {
5017 OtherRefType = OtherRef->getPointeeType();
5018 OtherQuals = OtherRefType.getQualifiers();
5019 }
5020
5021 // Our location for everything implicitly-generated.
5022 SourceLocation Loc = CopyAssignOperator->getLocation();
5023
5024 // Construct a reference to the "other" object. We'll be using this
5025 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005026 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005027 assert(OtherRef && "Reference to parameter cannot fail!");
5028
5029 // Construct the "this" pointer. We'll be using this throughout the generated
5030 // ASTs.
5031 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5032 assert(This && "Reference to this cannot fail!");
5033
5034 // Assign base classes.
5035 bool Invalid = false;
5036 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5037 E = ClassDecl->bases_end(); Base != E; ++Base) {
5038 // Form the assignment:
5039 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5040 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005041 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005042 Invalid = true;
5043 continue;
5044 }
5045
John McCallcf142162010-08-07 06:22:56 +00005046 CXXCastPath BasePath;
5047 BasePath.push_back(Base);
5048
Douglas Gregorb139cd52010-05-01 20:49:11 +00005049 // Construct the "from" expression, which is an implicit cast to the
5050 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005051 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005052 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005053 CK_UncheckedDerivedToBase,
5054 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005055
5056 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005057 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005058
5059 // Implicitly cast "this" to the appropriately-qualified base type.
5060 Expr *ToE = To.takeAs<Expr>();
5061 ImpCastExprToType(ToE,
5062 Context.getCVRQualifiedType(BaseType,
5063 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005064 CK_UncheckedDerivedToBase,
5065 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005066 To = Owned(ToE);
5067
5068 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005069 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005070 To.get(), From,
5071 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005072 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005073 Diag(CurrentLocation, diag::note_member_synthesized_at)
5074 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5075 CopyAssignOperator->setInvalidDecl();
5076 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005077 }
5078
5079 // Success! Record the copy.
5080 Statements.push_back(Copy.takeAs<Expr>());
5081 }
5082
5083 // \brief Reference to the __builtin_memcpy function.
5084 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005085 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005086 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005087
5088 // Assign non-static members.
5089 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5090 FieldEnd = ClassDecl->field_end();
5091 Field != FieldEnd; ++Field) {
5092 // Check for members of reference type; we can't copy those.
5093 if (Field->getType()->isReferenceType()) {
5094 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5095 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5096 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005097 Diag(CurrentLocation, diag::note_member_synthesized_at)
5098 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005099 Invalid = true;
5100 continue;
5101 }
5102
5103 // Check for members of const-qualified, non-class type.
5104 QualType BaseType = Context.getBaseElementType(Field->getType());
5105 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5106 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5107 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5108 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005109 Diag(CurrentLocation, diag::note_member_synthesized_at)
5110 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005111 Invalid = true;
5112 continue;
5113 }
5114
5115 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005116 if (FieldType->isIncompleteArrayType()) {
5117 assert(ClassDecl->hasFlexibleArrayMember() &&
5118 "Incomplete array type is not valid");
5119 continue;
5120 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005121
5122 // Build references to the field in the object we're copying from and to.
5123 CXXScopeSpec SS; // Intentionally empty
5124 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5125 LookupMemberName);
5126 MemberLookup.addDecl(*Field);
5127 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005128 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005129 Loc, /*IsArrow=*/false,
5130 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005131 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005132 Loc, /*IsArrow=*/true,
5133 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005134 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5135 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5136
5137 // If the field should be copied with __builtin_memcpy rather than via
5138 // explicit assignments, do so. This optimization only applies for arrays
5139 // of scalars and arrays of class type with trivial copy-assignment
5140 // operators.
5141 if (FieldType->isArrayType() &&
5142 (!BaseType->isRecordType() ||
5143 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5144 ->hasTrivialCopyAssignment())) {
5145 // Compute the size of the memory buffer to be copied.
5146 QualType SizeType = Context.getSizeType();
5147 llvm::APInt Size(Context.getTypeSize(SizeType),
5148 Context.getTypeSizeInChars(BaseType).getQuantity());
5149 for (const ConstantArrayType *Array
5150 = Context.getAsConstantArrayType(FieldType);
5151 Array;
5152 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005153 llvm::APInt ArraySize
5154 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005155 Size *= ArraySize;
5156 }
5157
5158 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005159 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5160 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005161
5162 bool NeedsCollectableMemCpy =
5163 (BaseType->isRecordType() &&
5164 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5165
5166 if (NeedsCollectableMemCpy) {
5167 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005168 // Create a reference to the __builtin_objc_memmove_collectable function.
5169 LookupResult R(*this,
5170 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005171 Loc, LookupOrdinaryName);
5172 LookupName(R, TUScope, true);
5173
5174 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5175 if (!CollectableMemCpy) {
5176 // Something went horribly wrong earlier, and we will have
5177 // complained about it.
5178 Invalid = true;
5179 continue;
5180 }
5181
5182 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5183 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005184 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005185 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5186 }
5187 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005188 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005189 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005190 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5191 LookupOrdinaryName);
5192 LookupName(R, TUScope, true);
5193
5194 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5195 if (!BuiltinMemCpy) {
5196 // Something went horribly wrong earlier, and we will have complained
5197 // about it.
5198 Invalid = true;
5199 continue;
5200 }
5201
5202 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5203 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005204 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005205 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5206 }
5207
John McCall37ad5512010-08-23 06:44:23 +00005208 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005209 CallArgs.push_back(To.takeAs<Expr>());
5210 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005211 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005212 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005213 if (NeedsCollectableMemCpy)
5214 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005215 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005216 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005217 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005218 else
5219 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005220 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005221 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005222 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005223
Douglas Gregorb139cd52010-05-01 20:49:11 +00005224 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5225 Statements.push_back(Call.takeAs<Expr>());
5226 continue;
5227 }
5228
5229 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005230 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005231 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005232 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005233 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005234 Diag(CurrentLocation, diag::note_member_synthesized_at)
5235 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5236 CopyAssignOperator->setInvalidDecl();
5237 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005238 }
5239
5240 // Success! Record the copy.
5241 Statements.push_back(Copy.takeAs<Stmt>());
5242 }
5243
5244 if (!Invalid) {
5245 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005246 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005247
John McCalldadc5752010-08-24 06:29:42 +00005248 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005249 if (Return.isInvalid())
5250 Invalid = true;
5251 else {
5252 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005253
5254 if (Trap.hasErrorOccurred()) {
5255 Diag(CurrentLocation, diag::note_member_synthesized_at)
5256 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5257 Invalid = true;
5258 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005259 }
5260 }
5261
5262 if (Invalid) {
5263 CopyAssignOperator->setInvalidDecl();
5264 return;
5265 }
5266
John McCalldadc5752010-08-24 06:29:42 +00005267 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005268 /*isStmtExpr=*/false);
5269 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5270 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005271}
5272
Douglas Gregor0be31a22010-07-02 17:43:08 +00005273CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5274 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005275 // C++ [class.copy]p4:
5276 // If the class definition does not explicitly declare a copy
5277 // constructor, one is declared implicitly.
5278
Douglas Gregor54be3392010-07-01 17:57:27 +00005279 // C++ [class.copy]p5:
5280 // The implicitly-declared copy constructor for a class X will
5281 // have the form
5282 //
5283 // X::X(const X&)
5284 //
5285 // if
5286 bool HasConstCopyConstructor = true;
5287
5288 // -- each direct or virtual base class B of X has a copy
5289 // constructor whose first parameter is of type const B& or
5290 // const volatile B&, and
5291 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5292 BaseEnd = ClassDecl->bases_end();
5293 HasConstCopyConstructor && Base != BaseEnd;
5294 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005295 // Virtual bases are handled below.
5296 if (Base->isVirtual())
5297 continue;
5298
Douglas Gregora6d69502010-07-02 23:41:54 +00005299 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005300 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005301 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5302 DeclareImplicitCopyConstructor(BaseClassDecl);
5303
Douglas Gregorcfe68222010-07-01 18:27:03 +00005304 HasConstCopyConstructor
5305 = BaseClassDecl->hasConstCopyConstructor(Context);
5306 }
5307
5308 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5309 BaseEnd = ClassDecl->vbases_end();
5310 HasConstCopyConstructor && Base != BaseEnd;
5311 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005312 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005313 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005314 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5315 DeclareImplicitCopyConstructor(BaseClassDecl);
5316
Douglas Gregor54be3392010-07-01 17:57:27 +00005317 HasConstCopyConstructor
5318 = BaseClassDecl->hasConstCopyConstructor(Context);
5319 }
5320
5321 // -- for all the nonstatic data members of X that are of a
5322 // class type M (or array thereof), each such class type
5323 // has a copy constructor whose first parameter is of type
5324 // const M& or const volatile M&.
5325 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5326 FieldEnd = ClassDecl->field_end();
5327 HasConstCopyConstructor && Field != FieldEnd;
5328 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005329 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005330 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005331 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005332 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005333 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5334 DeclareImplicitCopyConstructor(FieldClassDecl);
5335
Douglas Gregor54be3392010-07-01 17:57:27 +00005336 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005337 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005338 }
5339 }
5340
5341 // Otherwise, the implicitly declared copy constructor will have
5342 // the form
5343 //
5344 // X::X(X&)
5345 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5346 QualType ArgType = ClassType;
5347 if (HasConstCopyConstructor)
5348 ArgType = ArgType.withConst();
5349 ArgType = Context.getLValueReferenceType(ArgType);
5350
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005351 // C++ [except.spec]p14:
5352 // An implicitly declared special member function (Clause 12) shall have an
5353 // exception-specification. [...]
5354 ImplicitExceptionSpecification ExceptSpec(Context);
5355 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5356 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5357 BaseEnd = ClassDecl->bases_end();
5358 Base != BaseEnd;
5359 ++Base) {
5360 // Virtual bases are handled below.
5361 if (Base->isVirtual())
5362 continue;
5363
Douglas Gregora6d69502010-07-02 23:41:54 +00005364 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005365 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005366 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5367 DeclareImplicitCopyConstructor(BaseClassDecl);
5368
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005369 if (CXXConstructorDecl *CopyConstructor
5370 = BaseClassDecl->getCopyConstructor(Context, Quals))
5371 ExceptSpec.CalledDecl(CopyConstructor);
5372 }
5373 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5374 BaseEnd = ClassDecl->vbases_end();
5375 Base != BaseEnd;
5376 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005377 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005378 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005379 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5380 DeclareImplicitCopyConstructor(BaseClassDecl);
5381
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005382 if (CXXConstructorDecl *CopyConstructor
5383 = BaseClassDecl->getCopyConstructor(Context, Quals))
5384 ExceptSpec.CalledDecl(CopyConstructor);
5385 }
5386 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5387 FieldEnd = ClassDecl->field_end();
5388 Field != FieldEnd;
5389 ++Field) {
5390 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5391 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005392 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005393 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005394 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5395 DeclareImplicitCopyConstructor(FieldClassDecl);
5396
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005397 if (CXXConstructorDecl *CopyConstructor
5398 = FieldClassDecl->getCopyConstructor(Context, Quals))
5399 ExceptSpec.CalledDecl(CopyConstructor);
5400 }
5401 }
5402
Douglas Gregor54be3392010-07-01 17:57:27 +00005403 // An implicitly-declared copy constructor is an inline public
5404 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005405 FunctionProtoType::ExtProtoInfo EPI;
5406 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5407 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5408 EPI.NumExceptions = ExceptSpec.size();
5409 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005410 DeclarationName Name
5411 = Context.DeclarationNames.getCXXConstructorName(
5412 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005413 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005414 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005415 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005416 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005417 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005418 /*TInfo=*/0,
5419 /*isExplicit=*/false,
5420 /*isInline=*/true,
5421 /*isImplicitlyDeclared=*/true);
5422 CopyConstructor->setAccess(AS_public);
5423 CopyConstructor->setImplicit();
5424 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5425
Douglas Gregora6d69502010-07-02 23:41:54 +00005426 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005427 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5428
Douglas Gregor54be3392010-07-01 17:57:27 +00005429 // Add the parameter to the constructor.
5430 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5431 ClassDecl->getLocation(),
5432 /*IdentifierInfo=*/0,
5433 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005434 SC_None,
5435 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005436 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005437 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005438 PushOnScopeChains(CopyConstructor, S, false);
5439 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005440
5441 return CopyConstructor;
5442}
5443
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005444void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5445 CXXConstructorDecl *CopyConstructor,
5446 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005447 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005448 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005449 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005450 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005451
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005452 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005453 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005454
Douglas Gregora57478e2010-05-01 15:04:51 +00005455 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005456 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005457
Alexis Hunt1d792652011-01-08 20:30:50 +00005458 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005459 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005460 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005461 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005462 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005463 } else {
5464 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5465 CopyConstructor->getLocation(),
5466 MultiStmtArg(*this, 0, 0),
5467 /*isStmtExpr=*/false)
5468 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005469 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005470
5471 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005472}
5473
John McCalldadc5752010-08-24 06:29:42 +00005474ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005475Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005476 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005477 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005478 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005479 unsigned ConstructKind,
5480 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005481 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005482
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005483 // C++0x [class.copy]p34:
5484 // When certain criteria are met, an implementation is allowed to
5485 // omit the copy/move construction of a class object, even if the
5486 // copy/move constructor and/or destructor for the object have
5487 // side effects. [...]
5488 // - when a temporary class object that has not been bound to a
5489 // reference (12.2) would be copied/moved to a class object
5490 // with the same cv-unqualified type, the copy/move operation
5491 // can be omitted by constructing the temporary object
5492 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005493 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5494 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005495 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005496 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005497 }
Mike Stump11289f42009-09-09 15:08:12 +00005498
5499 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005500 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005501 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005502}
5503
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005504/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5505/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005506ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005507Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5508 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005509 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005510 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005511 unsigned ConstructKind,
5512 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005513 unsigned NumExprs = ExprArgs.size();
5514 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005515
Douglas Gregor27381f32009-11-23 12:27:39 +00005516 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005517 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005518 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005519 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005520 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5521 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005522}
5523
Mike Stump11289f42009-09-09 15:08:12 +00005524bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005525 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005526 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005527 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005528 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005529 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005530 move(Exprs), false, CXXConstructExpr::CK_Complete,
5531 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005532 if (TempResult.isInvalid())
5533 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005534
Anders Carlsson6eb55572009-08-25 05:12:04 +00005535 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005536 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005537 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005538 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005539 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005540
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005541 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005542}
5543
John McCall03c48482010-02-02 09:10:11 +00005544void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5545 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005546 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005547 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005548 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005549 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005550 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005551 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005552 << VD->getDeclName()
5553 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005554
John McCall386dfc72010-09-18 05:25:11 +00005555 // TODO: this should be re-enabled for static locals by !CXAAtExit
5556 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005557 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005558 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005559}
5560
Mike Stump11289f42009-09-09 15:08:12 +00005561/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005562/// ActOnDeclarator, when a C++ direct initializer is present.
5563/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005564void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005565 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005566 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005567 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005568 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005569
5570 // If there is no declaration, there was an error parsing it. Just ignore
5571 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005572 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005573 return;
Mike Stump11289f42009-09-09 15:08:12 +00005574
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005575 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5576 if (!VDecl) {
5577 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5578 RealDecl->setInvalidDecl();
5579 return;
5580 }
5581
Douglas Gregor402250f2009-08-26 21:14:46 +00005582 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005583 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005584 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5585 //
5586 // Clients that want to distinguish between the two forms, can check for
5587 // direct initializer using VarDecl::hasCXXDirectInitializer().
5588 // A major benefit is that clients that don't particularly care about which
5589 // exactly form was it (like the CodeGen) can handle both cases without
5590 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005591
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005592 // C++ 8.5p11:
5593 // The form of initialization (using parentheses or '=') is generally
5594 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005595 // class type.
5596
Douglas Gregor50dc2192010-02-11 22:55:30 +00005597 if (!VDecl->getType()->isDependentType() &&
5598 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005599 diag::err_typecheck_decl_incomplete_type)) {
5600 VDecl->setInvalidDecl();
5601 return;
5602 }
5603
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005604 // The variable can not have an abstract class type.
5605 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5606 diag::err_abstract_type_in_decl,
5607 AbstractVariableType))
5608 VDecl->setInvalidDecl();
5609
Sebastian Redl5ca79842010-02-01 20:16:42 +00005610 const VarDecl *Def;
5611 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005612 Diag(VDecl->getLocation(), diag::err_redefinition)
5613 << VDecl->getDeclName();
5614 Diag(Def->getLocation(), diag::note_previous_definition);
5615 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005616 return;
5617 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005618
Douglas Gregorf0f83692010-08-24 05:27:49 +00005619 // C++ [class.static.data]p4
5620 // If a static data member is of const integral or const
5621 // enumeration type, its declaration in the class definition can
5622 // specify a constant-initializer which shall be an integral
5623 // constant expression (5.19). In that case, the member can appear
5624 // in integral constant expressions. The member shall still be
5625 // defined in a namespace scope if it is used in the program and the
5626 // namespace scope definition shall not contain an initializer.
5627 //
5628 // We already performed a redefinition check above, but for static
5629 // data members we also need to check whether there was an in-class
5630 // declaration with an initializer.
5631 const VarDecl* PrevInit = 0;
5632 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5633 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5634 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5635 return;
5636 }
5637
Douglas Gregor71f39c92010-12-16 01:31:22 +00005638 bool IsDependent = false;
5639 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5640 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5641 VDecl->setInvalidDecl();
5642 return;
5643 }
5644
5645 if (Exprs.get()[I]->isTypeDependent())
5646 IsDependent = true;
5647 }
5648
Douglas Gregor50dc2192010-02-11 22:55:30 +00005649 // If either the declaration has a dependent type or if any of the
5650 // expressions is type-dependent, we represent the initialization
5651 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005652 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005653 // Let clients know that initialization was done with a direct initializer.
5654 VDecl->setCXXDirectInitializer(true);
5655
5656 // Store the initialization expressions as a ParenListExpr.
5657 unsigned NumExprs = Exprs.size();
5658 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5659 (Expr **)Exprs.release(),
5660 NumExprs, RParenLoc));
5661 return;
5662 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005663
5664 // Capture the variable that is being initialized and the style of
5665 // initialization.
5666 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5667
5668 // FIXME: Poor source location information.
5669 InitializationKind Kind
5670 = InitializationKind::CreateDirect(VDecl->getLocation(),
5671 LParenLoc, RParenLoc);
5672
5673 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005674 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005675 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005676 if (Result.isInvalid()) {
5677 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005678 return;
5679 }
John McCallacf0ee52010-10-08 02:01:28 +00005680
5681 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005682
Douglas Gregora40433a2010-12-07 00:41:46 +00005683 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005684 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005685 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005686
John McCall8b7fd8f12011-01-19 11:48:09 +00005687 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005688}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005689
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005690/// \brief Given a constructor and the set of arguments provided for the
5691/// constructor, convert the arguments and add any required default arguments
5692/// to form a proper call to this constructor.
5693///
5694/// \returns true if an error occurred, false otherwise.
5695bool
5696Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5697 MultiExprArg ArgsPtr,
5698 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005699 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005700 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5701 unsigned NumArgs = ArgsPtr.size();
5702 Expr **Args = (Expr **)ArgsPtr.get();
5703
5704 const FunctionProtoType *Proto
5705 = Constructor->getType()->getAs<FunctionProtoType>();
5706 assert(Proto && "Constructor without a prototype?");
5707 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005708
5709 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005710 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005711 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005712 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005713 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005714
5715 VariadicCallType CallType =
5716 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5717 llvm::SmallVector<Expr *, 8> AllArgs;
5718 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5719 Proto, 0, Args, NumArgs, AllArgs,
5720 CallType);
5721 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5722 ConvertedArgs.push_back(AllArgs[i]);
5723 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005724}
5725
Anders Carlssone363c8e2009-12-12 00:32:00 +00005726static inline bool
5727CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5728 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005729 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005730 if (isa<NamespaceDecl>(DC)) {
5731 return SemaRef.Diag(FnDecl->getLocation(),
5732 diag::err_operator_new_delete_declared_in_namespace)
5733 << FnDecl->getDeclName();
5734 }
5735
5736 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005737 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005738 return SemaRef.Diag(FnDecl->getLocation(),
5739 diag::err_operator_new_delete_declared_static)
5740 << FnDecl->getDeclName();
5741 }
5742
Anders Carlsson60659a82009-12-12 02:43:16 +00005743 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005744}
5745
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005746static inline bool
5747CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5748 CanQualType ExpectedResultType,
5749 CanQualType ExpectedFirstParamType,
5750 unsigned DependentParamTypeDiag,
5751 unsigned InvalidParamTypeDiag) {
5752 QualType ResultType =
5753 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5754
5755 // Check that the result type is not dependent.
5756 if (ResultType->isDependentType())
5757 return SemaRef.Diag(FnDecl->getLocation(),
5758 diag::err_operator_new_delete_dependent_result_type)
5759 << FnDecl->getDeclName() << ExpectedResultType;
5760
5761 // Check that the result type is what we expect.
5762 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5763 return SemaRef.Diag(FnDecl->getLocation(),
5764 diag::err_operator_new_delete_invalid_result_type)
5765 << FnDecl->getDeclName() << ExpectedResultType;
5766
5767 // A function template must have at least 2 parameters.
5768 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5769 return SemaRef.Diag(FnDecl->getLocation(),
5770 diag::err_operator_new_delete_template_too_few_parameters)
5771 << FnDecl->getDeclName();
5772
5773 // The function decl must have at least 1 parameter.
5774 if (FnDecl->getNumParams() == 0)
5775 return SemaRef.Diag(FnDecl->getLocation(),
5776 diag::err_operator_new_delete_too_few_parameters)
5777 << FnDecl->getDeclName();
5778
5779 // Check the the first parameter type is not dependent.
5780 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5781 if (FirstParamType->isDependentType())
5782 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5783 << FnDecl->getDeclName() << ExpectedFirstParamType;
5784
5785 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005786 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005787 ExpectedFirstParamType)
5788 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5789 << FnDecl->getDeclName() << ExpectedFirstParamType;
5790
5791 return false;
5792}
5793
Anders Carlsson12308f42009-12-11 23:23:22 +00005794static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005795CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005796 // C++ [basic.stc.dynamic.allocation]p1:
5797 // A program is ill-formed if an allocation function is declared in a
5798 // namespace scope other than global scope or declared static in global
5799 // scope.
5800 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5801 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005802
5803 CanQualType SizeTy =
5804 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5805
5806 // C++ [basic.stc.dynamic.allocation]p1:
5807 // The return type shall be void*. The first parameter shall have type
5808 // std::size_t.
5809 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5810 SizeTy,
5811 diag::err_operator_new_dependent_param_type,
5812 diag::err_operator_new_param_type))
5813 return true;
5814
5815 // C++ [basic.stc.dynamic.allocation]p1:
5816 // The first parameter shall not have an associated default argument.
5817 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005818 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005819 diag::err_operator_new_default_arg)
5820 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5821
5822 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005823}
5824
5825static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005826CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5827 // C++ [basic.stc.dynamic.deallocation]p1:
5828 // A program is ill-formed if deallocation functions are declared in a
5829 // namespace scope other than global scope or declared static in global
5830 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005831 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5832 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005833
5834 // C++ [basic.stc.dynamic.deallocation]p2:
5835 // Each deallocation function shall return void and its first parameter
5836 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005837 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5838 SemaRef.Context.VoidPtrTy,
5839 diag::err_operator_delete_dependent_param_type,
5840 diag::err_operator_delete_param_type))
5841 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005842
Anders Carlsson12308f42009-12-11 23:23:22 +00005843 return false;
5844}
5845
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005846/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5847/// of this overloaded operator is well-formed. If so, returns false;
5848/// otherwise, emits appropriate diagnostics and returns true.
5849bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005850 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005851 "Expected an overloaded operator declaration");
5852
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005853 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5854
Mike Stump11289f42009-09-09 15:08:12 +00005855 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005856 // The allocation and deallocation functions, operator new,
5857 // operator new[], operator delete and operator delete[], are
5858 // described completely in 3.7.3. The attributes and restrictions
5859 // found in the rest of this subclause do not apply to them unless
5860 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005861 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005862 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005863
Anders Carlsson22f443f2009-12-12 00:26:23 +00005864 if (Op == OO_New || Op == OO_Array_New)
5865 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005866
5867 // C++ [over.oper]p6:
5868 // An operator function shall either be a non-static member
5869 // function or be a non-member function and have at least one
5870 // parameter whose type is a class, a reference to a class, an
5871 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005872 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5873 if (MethodDecl->isStatic())
5874 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005875 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005876 } else {
5877 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005878 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5879 ParamEnd = FnDecl->param_end();
5880 Param != ParamEnd; ++Param) {
5881 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005882 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5883 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005884 ClassOrEnumParam = true;
5885 break;
5886 }
5887 }
5888
Douglas Gregord69246b2008-11-17 16:14:12 +00005889 if (!ClassOrEnumParam)
5890 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005891 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005892 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005893 }
5894
5895 // C++ [over.oper]p8:
5896 // An operator function cannot have default arguments (8.3.6),
5897 // except where explicitly stated below.
5898 //
Mike Stump11289f42009-09-09 15:08:12 +00005899 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005900 // (C++ [over.call]p1).
5901 if (Op != OO_Call) {
5902 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5903 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005904 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005905 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005906 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005907 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005908 }
5909 }
5910
Douglas Gregor6cf08062008-11-10 13:38:07 +00005911 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5912 { false, false, false }
5913#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5914 , { Unary, Binary, MemberOnly }
5915#include "clang/Basic/OperatorKinds.def"
5916 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005917
Douglas Gregor6cf08062008-11-10 13:38:07 +00005918 bool CanBeUnaryOperator = OperatorUses[Op][0];
5919 bool CanBeBinaryOperator = OperatorUses[Op][1];
5920 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005921
5922 // C++ [over.oper]p8:
5923 // [...] Operator functions cannot have more or fewer parameters
5924 // than the number required for the corresponding operator, as
5925 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005926 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005927 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005928 if (Op != OO_Call &&
5929 ((NumParams == 1 && !CanBeUnaryOperator) ||
5930 (NumParams == 2 && !CanBeBinaryOperator) ||
5931 (NumParams < 1) || (NumParams > 2))) {
5932 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005933 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005934 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005935 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005936 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005937 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005938 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005939 assert(CanBeBinaryOperator &&
5940 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005941 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005942 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005943
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005944 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005945 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005946 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005947
Douglas Gregord69246b2008-11-17 16:14:12 +00005948 // Overloaded operators other than operator() cannot be variadic.
5949 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005950 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005951 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005952 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005953 }
5954
5955 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005956 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5957 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005958 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005959 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005960 }
5961
5962 // C++ [over.inc]p1:
5963 // The user-defined function called operator++ implements the
5964 // prefix and postfix ++ operator. If this function is a member
5965 // function with no parameters, or a non-member function with one
5966 // parameter of class or enumeration type, it defines the prefix
5967 // increment operator ++ for objects of that type. If the function
5968 // is a member function with one parameter (which shall be of type
5969 // int) or a non-member function with two parameters (the second
5970 // of which shall be of type int), it defines the postfix
5971 // increment operator ++ for objects of that type.
5972 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5973 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5974 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005975 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005976 ParamIsInt = BT->getKind() == BuiltinType::Int;
5977
Chris Lattner2b786902008-11-21 07:50:02 +00005978 if (!ParamIsInt)
5979 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005980 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005981 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005982 }
5983
Douglas Gregord69246b2008-11-17 16:14:12 +00005984 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005985}
Chris Lattner3b024a32008-12-17 07:09:26 +00005986
Alexis Huntc88db062010-01-13 09:01:02 +00005987/// CheckLiteralOperatorDeclaration - Check whether the declaration
5988/// of this literal operator function is well-formed. If so, returns
5989/// false; otherwise, emits appropriate diagnostics and returns true.
5990bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5991 DeclContext *DC = FnDecl->getDeclContext();
5992 Decl::Kind Kind = DC->getDeclKind();
5993 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5994 Kind != Decl::LinkageSpec) {
5995 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5996 << FnDecl->getDeclName();
5997 return true;
5998 }
5999
6000 bool Valid = false;
6001
Alexis Hunt7dd26172010-04-07 23:11:06 +00006002 // template <char...> type operator "" name() is the only valid template
6003 // signature, and the only valid signature with no parameters.
6004 if (FnDecl->param_size() == 0) {
6005 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6006 // Must have only one template parameter
6007 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6008 if (Params->size() == 1) {
6009 NonTypeTemplateParmDecl *PmDecl =
6010 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006011
Alexis Hunt7dd26172010-04-07 23:11:06 +00006012 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006013 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6014 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6015 Valid = true;
6016 }
6017 }
6018 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006019 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006020 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6021
Alexis Huntc88db062010-01-13 09:01:02 +00006022 QualType T = (*Param)->getType();
6023
Alexis Hunt079a6f72010-04-07 22:57:35 +00006024 // unsigned long long int, long double, and any character type are allowed
6025 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006026 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6027 Context.hasSameType(T, Context.LongDoubleTy) ||
6028 Context.hasSameType(T, Context.CharTy) ||
6029 Context.hasSameType(T, Context.WCharTy) ||
6030 Context.hasSameType(T, Context.Char16Ty) ||
6031 Context.hasSameType(T, Context.Char32Ty)) {
6032 if (++Param == FnDecl->param_end())
6033 Valid = true;
6034 goto FinishedParams;
6035 }
6036
Alexis Hunt079a6f72010-04-07 22:57:35 +00006037 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006038 const PointerType *PT = T->getAs<PointerType>();
6039 if (!PT)
6040 goto FinishedParams;
6041 T = PT->getPointeeType();
6042 if (!T.isConstQualified())
6043 goto FinishedParams;
6044 T = T.getUnqualifiedType();
6045
6046 // Move on to the second parameter;
6047 ++Param;
6048
6049 // If there is no second parameter, the first must be a const char *
6050 if (Param == FnDecl->param_end()) {
6051 if (Context.hasSameType(T, Context.CharTy))
6052 Valid = true;
6053 goto FinishedParams;
6054 }
6055
6056 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6057 // are allowed as the first parameter to a two-parameter function
6058 if (!(Context.hasSameType(T, Context.CharTy) ||
6059 Context.hasSameType(T, Context.WCharTy) ||
6060 Context.hasSameType(T, Context.Char16Ty) ||
6061 Context.hasSameType(T, Context.Char32Ty)))
6062 goto FinishedParams;
6063
6064 // The second and final parameter must be an std::size_t
6065 T = (*Param)->getType().getUnqualifiedType();
6066 if (Context.hasSameType(T, Context.getSizeType()) &&
6067 ++Param == FnDecl->param_end())
6068 Valid = true;
6069 }
6070
6071 // FIXME: This diagnostic is absolutely terrible.
6072FinishedParams:
6073 if (!Valid) {
6074 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6075 << FnDecl->getDeclName();
6076 return true;
6077 }
6078
6079 return false;
6080}
6081
Douglas Gregor07665a62009-01-05 19:45:36 +00006082/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6083/// linkage specification, including the language and (if present)
6084/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6085/// the location of the language string literal, which is provided
6086/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6087/// the '{' brace. Otherwise, this linkage specification does not
6088/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006089Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6090 SourceLocation LangLoc,
6091 llvm::StringRef Lang,
6092 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006093 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006094 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006095 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006096 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006097 Language = LinkageSpecDecl::lang_cxx;
6098 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006099 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006100 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006101 }
Mike Stump11289f42009-09-09 15:08:12 +00006102
Chris Lattner438e5012008-12-17 07:13:27 +00006103 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006104
Douglas Gregor07665a62009-01-05 19:45:36 +00006105 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006106 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006107 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006108 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006109 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006110 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006111}
6112
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006113/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006114/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6115/// valid, it's the position of the closing '}' brace in a linkage
6116/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006117Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6118 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006119 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006120 if (LinkageSpec)
6121 PopDeclContext();
6122 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006123}
6124
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006125/// \brief Perform semantic analysis for the variable declaration that
6126/// occurs within a C++ catch clause, returning the newly-created
6127/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006128VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006129 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006130 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006131 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006132 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006133 QualType ExDeclType = TInfo->getType();
6134
Sebastian Redl54c04d42008-12-22 19:15:10 +00006135 // Arrays and functions decay.
6136 if (ExDeclType->isArrayType())
6137 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6138 else if (ExDeclType->isFunctionType())
6139 ExDeclType = Context.getPointerType(ExDeclType);
6140
6141 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6142 // The exception-declaration shall not denote a pointer or reference to an
6143 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006144 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006145 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006146 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006147 Invalid = true;
6148 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006149
Douglas Gregor104ee002010-03-08 01:47:36 +00006150 // GCC allows catching pointers and references to incomplete types
6151 // as an extension; so do we, but we warn by default.
6152
Sebastian Redl54c04d42008-12-22 19:15:10 +00006153 QualType BaseType = ExDeclType;
6154 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006155 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006156 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006157 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006158 BaseType = Ptr->getPointeeType();
6159 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006160 DK = diag::ext_catch_incomplete_ptr;
6161 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006162 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006163 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006164 BaseType = Ref->getPointeeType();
6165 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006166 DK = diag::ext_catch_incomplete_ref;
6167 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006168 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006169 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006170 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6171 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006172 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006173
Mike Stump11289f42009-09-09 15:08:12 +00006174 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006175 RequireNonAbstractType(Loc, ExDeclType,
6176 diag::err_abstract_type_in_decl,
6177 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006178 Invalid = true;
6179
John McCall2ca705e2010-07-24 00:37:23 +00006180 // Only the non-fragile NeXT runtime currently supports C++ catches
6181 // of ObjC types, and no runtime supports catching ObjC types by value.
6182 if (!Invalid && getLangOptions().ObjC1) {
6183 QualType T = ExDeclType;
6184 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6185 T = RT->getPointeeType();
6186
6187 if (T->isObjCObjectType()) {
6188 Diag(Loc, diag::err_objc_object_catch);
6189 Invalid = true;
6190 } else if (T->isObjCObjectPointerType()) {
6191 if (!getLangOptions().NeXTRuntime) {
6192 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6193 Invalid = true;
6194 } else if (!getLangOptions().ObjCNonFragileABI) {
6195 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6196 Invalid = true;
6197 }
6198 }
6199 }
6200
Mike Stump11289f42009-09-09 15:08:12 +00006201 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006202 Name, ExDeclType, TInfo, SC_None,
6203 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006204 ExDecl->setExceptionVariable(true);
6205
Douglas Gregor6de584c2010-03-05 23:38:39 +00006206 if (!Invalid) {
6207 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6208 // C++ [except.handle]p16:
6209 // The object declared in an exception-declaration or, if the
6210 // exception-declaration does not specify a name, a temporary (12.2) is
6211 // copy-initialized (8.5) from the exception object. [...]
6212 // The object is destroyed when the handler exits, after the destruction
6213 // of any automatic objects initialized within the handler.
6214 //
6215 // We just pretend to initialize the object with itself, then make sure
6216 // it can be destroyed later.
6217 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6218 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006219 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006220 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6221 SourceLocation());
6222 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006223 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006224 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006225 if (Result.isInvalid())
6226 Invalid = true;
6227 else
6228 FinalizeVarWithDestructor(ExDecl, RecordTy);
6229 }
6230 }
6231
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006232 if (Invalid)
6233 ExDecl->setInvalidDecl();
6234
6235 return ExDecl;
6236}
6237
6238/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6239/// handler.
John McCall48871652010-08-21 09:40:31 +00006240Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006241 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006242 bool Invalid = D.isInvalidType();
6243
6244 // Check for unexpanded parameter packs.
6245 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6246 UPPC_ExceptionType)) {
6247 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6248 D.getIdentifierLoc());
6249 Invalid = true;
6250 }
6251
Sebastian Redl54c04d42008-12-22 19:15:10 +00006252 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006253 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006254 LookupOrdinaryName,
6255 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006256 // The scope should be freshly made just for us. There is just no way
6257 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006258 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006259 if (PrevDecl->isTemplateParameter()) {
6260 // Maybe we will complain about the shadowed template parameter.
6261 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006262 }
6263 }
6264
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006265 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006266 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6267 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006268 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006269 }
6270
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006271 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006272 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006273 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006274
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006275 if (Invalid)
6276 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006277
Sebastian Redl54c04d42008-12-22 19:15:10 +00006278 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006279 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006280 PushOnScopeChains(ExDecl, S);
6281 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006282 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006283
Douglas Gregor758a8692009-06-17 21:51:59 +00006284 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006285 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006286}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006287
John McCall48871652010-08-21 09:40:31 +00006288Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006289 Expr *AssertExpr,
6290 Expr *AssertMessageExpr_) {
6291 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006292
Anders Carlsson54b26982009-03-14 00:33:21 +00006293 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6294 llvm::APSInt Value(32);
6295 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6296 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6297 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006298 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006299 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006300
Anders Carlsson54b26982009-03-14 00:33:21 +00006301 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006302 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006303 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006304 }
6305 }
Mike Stump11289f42009-09-09 15:08:12 +00006306
Douglas Gregoref68fee2010-12-15 23:55:21 +00006307 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6308 return 0;
6309
Mike Stump11289f42009-09-09 15:08:12 +00006310 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006311 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006312
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006313 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006314 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006315}
Sebastian Redlf769df52009-03-24 22:27:57 +00006316
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006317/// \brief Perform semantic analysis of the given friend type declaration.
6318///
6319/// \returns A friend declaration that.
6320FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6321 TypeSourceInfo *TSInfo) {
6322 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6323
6324 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006325 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006326
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006327 if (!getLangOptions().CPlusPlus0x) {
6328 // C++03 [class.friend]p2:
6329 // An elaborated-type-specifier shall be used in a friend declaration
6330 // for a class.*
6331 //
6332 // * The class-key of the elaborated-type-specifier is required.
6333 if (!ActiveTemplateInstantiations.empty()) {
6334 // Do not complain about the form of friend template types during
6335 // template instantiation; we will already have complained when the
6336 // template was declared.
6337 } else if (!T->isElaboratedTypeSpecifier()) {
6338 // If we evaluated the type to a record type, suggest putting
6339 // a tag in front.
6340 if (const RecordType *RT = T->getAs<RecordType>()) {
6341 RecordDecl *RD = RT->getDecl();
6342
6343 std::string InsertionText = std::string(" ") + RD->getKindName();
6344
6345 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6346 << (unsigned) RD->getTagKind()
6347 << T
6348 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6349 InsertionText);
6350 } else {
6351 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6352 << T
6353 << SourceRange(FriendLoc, TypeRange.getEnd());
6354 }
6355 } else if (T->getAs<EnumType>()) {
6356 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006357 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006358 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006359 }
6360 }
6361
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006362 // C++0x [class.friend]p3:
6363 // If the type specifier in a friend declaration designates a (possibly
6364 // cv-qualified) class type, that class is declared as a friend; otherwise,
6365 // the friend declaration is ignored.
6366
6367 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6368 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006369
6370 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6371}
6372
John McCallace48cd2010-10-19 01:40:49 +00006373/// Handle a friend tag declaration where the scope specifier was
6374/// templated.
6375Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6376 unsigned TagSpec, SourceLocation TagLoc,
6377 CXXScopeSpec &SS,
6378 IdentifierInfo *Name, SourceLocation NameLoc,
6379 AttributeList *Attr,
6380 MultiTemplateParamsArg TempParamLists) {
6381 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6382
6383 bool isExplicitSpecialization = false;
6384 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6385 bool Invalid = false;
6386
6387 if (TemplateParameterList *TemplateParams
6388 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6389 TempParamLists.get(),
6390 TempParamLists.size(),
6391 /*friend*/ true,
6392 isExplicitSpecialization,
6393 Invalid)) {
6394 --NumMatchedTemplateParamLists;
6395
6396 if (TemplateParams->size() > 0) {
6397 // This is a declaration of a class template.
6398 if (Invalid)
6399 return 0;
6400
6401 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6402 SS, Name, NameLoc, Attr,
6403 TemplateParams, AS_public).take();
6404 } else {
6405 // The "template<>" header is extraneous.
6406 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6407 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6408 isExplicitSpecialization = true;
6409 }
6410 }
6411
6412 if (Invalid) return 0;
6413
6414 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6415
6416 bool isAllExplicitSpecializations = true;
6417 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6418 if (TempParamLists.get()[I]->size()) {
6419 isAllExplicitSpecializations = false;
6420 break;
6421 }
6422 }
6423
6424 // FIXME: don't ignore attributes.
6425
6426 // If it's explicit specializations all the way down, just forget
6427 // about the template header and build an appropriate non-templated
6428 // friend. TODO: for source fidelity, remember the headers.
6429 if (isAllExplicitSpecializations) {
6430 ElaboratedTypeKeyword Keyword
6431 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6432 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6433 TagLoc, SS.getRange(), NameLoc);
6434 if (T.isNull())
6435 return 0;
6436
6437 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6438 if (isa<DependentNameType>(T)) {
6439 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6440 TL.setKeywordLoc(TagLoc);
6441 TL.setQualifierRange(SS.getRange());
6442 TL.setNameLoc(NameLoc);
6443 } else {
6444 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6445 TL.setKeywordLoc(TagLoc);
6446 TL.setQualifierRange(SS.getRange());
6447 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6448 }
6449
6450 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6451 TSI, FriendLoc);
6452 Friend->setAccess(AS_public);
6453 CurContext->addDecl(Friend);
6454 return Friend;
6455 }
6456
6457 // Handle the case of a templated-scope friend class. e.g.
6458 // template <class T> class A<T>::B;
6459 // FIXME: we don't support these right now.
6460 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6461 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6462 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6463 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6464 TL.setKeywordLoc(TagLoc);
6465 TL.setQualifierRange(SS.getRange());
6466 TL.setNameLoc(NameLoc);
6467
6468 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6469 TSI, FriendLoc);
6470 Friend->setAccess(AS_public);
6471 Friend->setUnsupportedFriend(true);
6472 CurContext->addDecl(Friend);
6473 return Friend;
6474}
6475
6476
John McCall11083da2009-09-16 22:47:08 +00006477/// Handle a friend type declaration. This works in tandem with
6478/// ActOnTag.
6479///
6480/// Notes on friend class templates:
6481///
6482/// We generally treat friend class declarations as if they were
6483/// declaring a class. So, for example, the elaborated type specifier
6484/// in a friend declaration is required to obey the restrictions of a
6485/// class-head (i.e. no typedefs in the scope chain), template
6486/// parameters are required to match up with simple template-ids, &c.
6487/// However, unlike when declaring a template specialization, it's
6488/// okay to refer to a template specialization without an empty
6489/// template parameter declaration, e.g.
6490/// friend class A<T>::B<unsigned>;
6491/// We permit this as a special case; if there are any template
6492/// parameters present at all, require proper matching, i.e.
6493/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006494Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006495 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006496 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006497
6498 assert(DS.isFriendSpecified());
6499 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6500
John McCall11083da2009-09-16 22:47:08 +00006501 // Try to convert the decl specifier to a type. This works for
6502 // friend templates because ActOnTag never produces a ClassTemplateDecl
6503 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006504 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006505 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6506 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006507 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006508 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006509
Douglas Gregor6c110f32010-12-16 01:14:37 +00006510 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6511 return 0;
6512
John McCall11083da2009-09-16 22:47:08 +00006513 // This is definitely an error in C++98. It's probably meant to
6514 // be forbidden in C++0x, too, but the specification is just
6515 // poorly written.
6516 //
6517 // The problem is with declarations like the following:
6518 // template <T> friend A<T>::foo;
6519 // where deciding whether a class C is a friend or not now hinges
6520 // on whether there exists an instantiation of A that causes
6521 // 'foo' to equal C. There are restrictions on class-heads
6522 // (which we declare (by fiat) elaborated friend declarations to
6523 // be) that makes this tractable.
6524 //
6525 // FIXME: handle "template <> friend class A<T>;", which
6526 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006527 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006528 Diag(Loc, diag::err_tagless_friend_type_template)
6529 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006530 return 0;
John McCall11083da2009-09-16 22:47:08 +00006531 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006532
John McCallaa74a0c2009-08-28 07:59:38 +00006533 // C++98 [class.friend]p1: A friend of a class is a function
6534 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006535 // This is fixed in DR77, which just barely didn't make the C++03
6536 // deadline. It's also a very silly restriction that seriously
6537 // affects inner classes and which nobody else seems to implement;
6538 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006539 //
6540 // But note that we could warn about it: it's always useless to
6541 // friend one of your own members (it's not, however, worthless to
6542 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006543
John McCall11083da2009-09-16 22:47:08 +00006544 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006545 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006546 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006547 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006548 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006549 TSI,
John McCall11083da2009-09-16 22:47:08 +00006550 DS.getFriendSpecLoc());
6551 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006552 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6553
6554 if (!D)
John McCall48871652010-08-21 09:40:31 +00006555 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006556
John McCall11083da2009-09-16 22:47:08 +00006557 D->setAccess(AS_public);
6558 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006559
John McCall48871652010-08-21 09:40:31 +00006560 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006561}
6562
John McCallde3fd222010-10-12 23:13:28 +00006563Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6564 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006565 const DeclSpec &DS = D.getDeclSpec();
6566
6567 assert(DS.isFriendSpecified());
6568 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6569
6570 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006571 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6572 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006573
6574 // C++ [class.friend]p1
6575 // A friend of a class is a function or class....
6576 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006577 // It *doesn't* see through dependent types, which is correct
6578 // according to [temp.arg.type]p3:
6579 // If a declaration acquires a function type through a
6580 // type dependent on a template-parameter and this causes
6581 // a declaration that does not use the syntactic form of a
6582 // function declarator to have a function type, the program
6583 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006584 if (!T->isFunctionType()) {
6585 Diag(Loc, diag::err_unexpected_friend);
6586
6587 // It might be worthwhile to try to recover by creating an
6588 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006589 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006590 }
6591
6592 // C++ [namespace.memdef]p3
6593 // - If a friend declaration in a non-local class first declares a
6594 // class or function, the friend class or function is a member
6595 // of the innermost enclosing namespace.
6596 // - The name of the friend is not found by simple name lookup
6597 // until a matching declaration is provided in that namespace
6598 // scope (either before or after the class declaration granting
6599 // friendship).
6600 // - If a friend function is called, its name may be found by the
6601 // name lookup that considers functions from namespaces and
6602 // classes associated with the types of the function arguments.
6603 // - When looking for a prior declaration of a class or a function
6604 // declared as a friend, scopes outside the innermost enclosing
6605 // namespace scope are not considered.
6606
John McCallde3fd222010-10-12 23:13:28 +00006607 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006608 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6609 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006610 assert(Name);
6611
Douglas Gregor6c110f32010-12-16 01:14:37 +00006612 // Check for unexpanded parameter packs.
6613 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6614 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6615 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6616 return 0;
6617
John McCall07e91c02009-08-06 02:15:43 +00006618 // The context we found the declaration in, or in which we should
6619 // create the declaration.
6620 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006621 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006622 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006623 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006624
John McCallde3fd222010-10-12 23:13:28 +00006625 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006626
John McCallde3fd222010-10-12 23:13:28 +00006627 // There are four cases here.
6628 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006629 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006630 // there as appropriate.
6631 // Recover from invalid scope qualifiers as if they just weren't there.
6632 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006633 // C++0x [namespace.memdef]p3:
6634 // If the name in a friend declaration is neither qualified nor
6635 // a template-id and the declaration is a function or an
6636 // elaborated-type-specifier, the lookup to determine whether
6637 // the entity has been previously declared shall not consider
6638 // any scopes outside the innermost enclosing namespace.
6639 // C++0x [class.friend]p11:
6640 // If a friend declaration appears in a local class and the name
6641 // specified is an unqualified name, a prior declaration is
6642 // looked up without considering scopes that are outside the
6643 // innermost enclosing non-class scope. For a friend function
6644 // declaration, if there is no prior declaration, the program is
6645 // ill-formed.
6646 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006647 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006648
John McCallf7cfb222010-10-13 05:45:15 +00006649 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006650 DC = CurContext;
6651 while (true) {
6652 // Skip class contexts. If someone can cite chapter and verse
6653 // for this behavior, that would be nice --- it's what GCC and
6654 // EDG do, and it seems like a reasonable intent, but the spec
6655 // really only says that checks for unqualified existing
6656 // declarations should stop at the nearest enclosing namespace,
6657 // not that they should only consider the nearest enclosing
6658 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006659 while (DC->isRecord())
6660 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006661
John McCall1f82f242009-11-18 22:49:29 +00006662 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006663
6664 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006665 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006666 break;
John McCallf7cfb222010-10-13 05:45:15 +00006667
John McCallf4776592010-10-14 22:22:28 +00006668 if (isTemplateId) {
6669 if (isa<TranslationUnitDecl>(DC)) break;
6670 } else {
6671 if (DC->isFileContext()) break;
6672 }
John McCall07e91c02009-08-06 02:15:43 +00006673 DC = DC->getParent();
6674 }
6675
6676 // C++ [class.friend]p1: A friend of a class is a function or
6677 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006678 // C++0x changes this for both friend types and functions.
6679 // Most C++ 98 compilers do seem to give an error here, so
6680 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006681 if (!Previous.empty() && DC->Equals(CurContext)
6682 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006683 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006684
John McCallccbc0322010-10-13 06:22:15 +00006685 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006686
John McCallde3fd222010-10-12 23:13:28 +00006687 // - There's a non-dependent scope specifier, in which case we
6688 // compute it and do a previous lookup there for a function
6689 // or function template.
6690 } else if (!SS.getScopeRep()->isDependent()) {
6691 DC = computeDeclContext(SS);
6692 if (!DC) return 0;
6693
6694 if (RequireCompleteDeclContext(SS, DC)) return 0;
6695
6696 LookupQualifiedName(Previous, DC);
6697
6698 // Ignore things found implicitly in the wrong scope.
6699 // TODO: better diagnostics for this case. Suggesting the right
6700 // qualified scope would be nice...
6701 LookupResult::Filter F = Previous.makeFilter();
6702 while (F.hasNext()) {
6703 NamedDecl *D = F.next();
6704 if (!DC->InEnclosingNamespaceSetOf(
6705 D->getDeclContext()->getRedeclContext()))
6706 F.erase();
6707 }
6708 F.done();
6709
6710 if (Previous.empty()) {
6711 D.setInvalidType();
6712 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6713 return 0;
6714 }
6715
6716 // C++ [class.friend]p1: A friend of a class is a function or
6717 // class that is not a member of the class . . .
6718 if (DC->Equals(CurContext))
6719 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6720
6721 // - There's a scope specifier that does not match any template
6722 // parameter lists, in which case we use some arbitrary context,
6723 // create a method or method template, and wait for instantiation.
6724 // - There's a scope specifier that does match some template
6725 // parameter lists, which we don't handle right now.
6726 } else {
6727 DC = CurContext;
6728 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006729 }
6730
John McCallf7cfb222010-10-13 05:45:15 +00006731 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006732 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006733 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6734 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6735 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006736 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006737 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6738 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006739 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006740 }
John McCall07e91c02009-08-06 02:15:43 +00006741 }
6742
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006743 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006744 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006745 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006746 IsDefinition,
6747 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006748 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006749
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006750 assert(ND->getDeclContext() == DC);
6751 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006752
John McCall759e32b2009-08-31 22:39:49 +00006753 // Add the function declaration to the appropriate lookup tables,
6754 // adjusting the redeclarations list as necessary. We don't
6755 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006756 //
John McCall759e32b2009-08-31 22:39:49 +00006757 // Also update the scope-based lookup if the target context's
6758 // lookup context is in lexical scope.
6759 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006760 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006761 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006762 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006763 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006764 }
John McCallaa74a0c2009-08-28 07:59:38 +00006765
6766 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006767 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006768 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006769 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006770 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006771
John McCallde3fd222010-10-12 23:13:28 +00006772 if (ND->isInvalidDecl())
6773 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006774 else {
6775 FunctionDecl *FD;
6776 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6777 FD = FTD->getTemplatedDecl();
6778 else
6779 FD = cast<FunctionDecl>(ND);
6780
6781 // Mark templated-scope function declarations as unsupported.
6782 if (FD->getNumTemplateParameterLists())
6783 FrD->setUnsupportedFriend(true);
6784 }
John McCallde3fd222010-10-12 23:13:28 +00006785
John McCall48871652010-08-21 09:40:31 +00006786 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006787}
6788
John McCall48871652010-08-21 09:40:31 +00006789void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6790 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006791
Sebastian Redlf769df52009-03-24 22:27:57 +00006792 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6793 if (!Fn) {
6794 Diag(DelLoc, diag::err_deleted_non_function);
6795 return;
6796 }
6797 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6798 Diag(DelLoc, diag::err_deleted_decl_not_first);
6799 Diag(Prev->getLocation(), diag::note_previous_declaration);
6800 // If the declaration wasn't the first, we delete the function anyway for
6801 // recovery.
6802 }
6803 Fn->setDeleted();
6804}
Sebastian Redl4c018662009-04-27 21:33:24 +00006805
6806static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6807 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6808 ++CI) {
6809 Stmt *SubStmt = *CI;
6810 if (!SubStmt)
6811 continue;
6812 if (isa<ReturnStmt>(SubStmt))
6813 Self.Diag(SubStmt->getSourceRange().getBegin(),
6814 diag::err_return_in_constructor_handler);
6815 if (!isa<Expr>(SubStmt))
6816 SearchForReturnInStmt(Self, SubStmt);
6817 }
6818}
6819
6820void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6821 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6822 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6823 SearchForReturnInStmt(*this, Handler);
6824 }
6825}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006826
Mike Stump11289f42009-09-09 15:08:12 +00006827bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006828 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006829 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6830 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006831
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006832 if (Context.hasSameType(NewTy, OldTy) ||
6833 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006834 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006835
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006836 // Check if the return types are covariant
6837 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006838
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006839 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006840 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6841 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006842 NewClassTy = NewPT->getPointeeType();
6843 OldClassTy = OldPT->getPointeeType();
6844 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006845 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6846 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6847 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6848 NewClassTy = NewRT->getPointeeType();
6849 OldClassTy = OldRT->getPointeeType();
6850 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006851 }
6852 }
Mike Stump11289f42009-09-09 15:08:12 +00006853
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006854 // The return types aren't either both pointers or references to a class type.
6855 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006856 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006857 diag::err_different_return_type_for_overriding_virtual_function)
6858 << New->getDeclName() << NewTy << OldTy;
6859 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006860
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006861 return true;
6862 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006863
Anders Carlssone60365b2009-12-31 18:34:24 +00006864 // C++ [class.virtual]p6:
6865 // If the return type of D::f differs from the return type of B::f, the
6866 // class type in the return type of D::f shall be complete at the point of
6867 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006868 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6869 if (!RT->isBeingDefined() &&
6870 RequireCompleteType(New->getLocation(), NewClassTy,
6871 PDiag(diag::err_covariant_return_incomplete)
6872 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006873 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006874 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006875
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006876 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006877 // Check if the new class derives from the old class.
6878 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6879 Diag(New->getLocation(),
6880 diag::err_covariant_return_not_derived)
6881 << New->getDeclName() << NewTy << OldTy;
6882 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6883 return true;
6884 }
Mike Stump11289f42009-09-09 15:08:12 +00006885
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006886 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006887 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006888 diag::err_covariant_return_inaccessible_base,
6889 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6890 // FIXME: Should this point to the return type?
6891 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006892 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6893 return true;
6894 }
6895 }
Mike Stump11289f42009-09-09 15:08:12 +00006896
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006897 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006898 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006899 Diag(New->getLocation(),
6900 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006901 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006902 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6903 return true;
6904 };
Mike Stump11289f42009-09-09 15:08:12 +00006905
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006906
6907 // The new class type must have the same or less qualifiers as the old type.
6908 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6909 Diag(New->getLocation(),
6910 diag::err_covariant_return_type_class_type_more_qualified)
6911 << New->getDeclName() << NewTy << OldTy;
6912 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6913 return true;
6914 };
Mike Stump11289f42009-09-09 15:08:12 +00006915
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006916 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006917}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006918
Alexis Hunt96d5c762009-11-21 08:43:09 +00006919bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6920 const CXXMethodDecl *Old)
6921{
6922 if (Old->hasAttr<FinalAttr>()) {
6923 Diag(New->getLocation(), diag::err_final_function_overridden)
6924 << New->getDeclName();
6925 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6926 return true;
6927 }
6928
6929 return false;
6930}
6931
Douglas Gregor21920e372009-12-01 17:24:26 +00006932/// \brief Mark the given method pure.
6933///
6934/// \param Method the method to be marked pure.
6935///
6936/// \param InitRange the source range that covers the "0" initializer.
6937bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6938 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6939 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006940 return false;
6941 }
6942
6943 if (!Method->isInvalidDecl())
6944 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6945 << Method->getDeclName() << InitRange;
6946 return true;
6947}
6948
John McCall1f4ee7b2009-12-19 09:28:58 +00006949/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6950/// an initializer for the out-of-line declaration 'Dcl'. The scope
6951/// is a fresh scope pushed for just this purpose.
6952///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006953/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6954/// static data member of class X, names should be looked up in the scope of
6955/// class X.
John McCall48871652010-08-21 09:40:31 +00006956void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006957 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006958 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006959
John McCall1f4ee7b2009-12-19 09:28:58 +00006960 // We should only get called for declarations with scope specifiers, like:
6961 // int foo::bar;
6962 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006963 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006964}
6965
6966/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006967/// initializer for the out-of-line declaration 'D'.
6968void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006969 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006970 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006971
John McCall1f4ee7b2009-12-19 09:28:58 +00006972 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006973 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006974}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006975
6976/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6977/// C++ if/switch/while/for statement.
6978/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006979DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006980 // C++ 6.4p2:
6981 // The declarator shall not specify a function or an array.
6982 // The type-specifier-seq shall not contain typedef and shall not declare a
6983 // new class or enumeration.
6984 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6985 "Parser allowed 'typedef' as storage class of condition decl.");
6986
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006987 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006988 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6989 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006990
6991 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6992 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6993 // would be created and CXXConditionDeclExpr wants a VarDecl.
6994 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6995 << D.getSourceRange();
6996 return DeclResult();
6997 } else if (OwnedTag && OwnedTag->isDefinition()) {
6998 // The type-specifier-seq shall not declare a new class or enumeration.
6999 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7000 }
7001
John McCall48871652010-08-21 09:40:31 +00007002 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007003 if (!Dcl)
7004 return DeclResult();
7005
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007006 return Dcl;
7007}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007008
Douglas Gregor88d292c2010-05-13 16:44:06 +00007009void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7010 bool DefinitionRequired) {
7011 // Ignore any vtable uses in unevaluated operands or for classes that do
7012 // not have a vtable.
7013 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7014 CurContext->isDependentContext() ||
7015 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007016 return;
7017
Douglas Gregor88d292c2010-05-13 16:44:06 +00007018 // Try to insert this class into the map.
7019 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7020 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7021 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7022 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007023 // If we already had an entry, check to see if we are promoting this vtable
7024 // to required a definition. If so, we need to reappend to the VTableUses
7025 // list, since we may have already processed the first entry.
7026 if (DefinitionRequired && !Pos.first->second) {
7027 Pos.first->second = true;
7028 } else {
7029 // Otherwise, we can early exit.
7030 return;
7031 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007032 }
7033
7034 // Local classes need to have their virtual members marked
7035 // immediately. For all other classes, we mark their virtual members
7036 // at the end of the translation unit.
7037 if (Class->isLocalClass())
7038 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007039 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007040 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007041}
7042
Douglas Gregor88d292c2010-05-13 16:44:06 +00007043bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007044 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007045 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007046
Douglas Gregor88d292c2010-05-13 16:44:06 +00007047 // Note: The VTableUses vector could grow as a result of marking
7048 // the members of a class as "used", so we check the size each
7049 // time through the loop and prefer indices (with are stable) to
7050 // iterators (which are not).
7051 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007052 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007053 if (!Class)
7054 continue;
7055
7056 SourceLocation Loc = VTableUses[I].second;
7057
7058 // If this class has a key function, but that key function is
7059 // defined in another translation unit, we don't need to emit the
7060 // vtable even though we're using it.
7061 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007062 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007063 switch (KeyFunction->getTemplateSpecializationKind()) {
7064 case TSK_Undeclared:
7065 case TSK_ExplicitSpecialization:
7066 case TSK_ExplicitInstantiationDeclaration:
7067 // The key function is in another translation unit.
7068 continue;
7069
7070 case TSK_ExplicitInstantiationDefinition:
7071 case TSK_ImplicitInstantiation:
7072 // We will be instantiating the key function.
7073 break;
7074 }
7075 } else if (!KeyFunction) {
7076 // If we have a class with no key function that is the subject
7077 // of an explicit instantiation declaration, suppress the
7078 // vtable; it will live with the explicit instantiation
7079 // definition.
7080 bool IsExplicitInstantiationDeclaration
7081 = Class->getTemplateSpecializationKind()
7082 == TSK_ExplicitInstantiationDeclaration;
7083 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7084 REnd = Class->redecls_end();
7085 R != REnd; ++R) {
7086 TemplateSpecializationKind TSK
7087 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7088 if (TSK == TSK_ExplicitInstantiationDeclaration)
7089 IsExplicitInstantiationDeclaration = true;
7090 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7091 IsExplicitInstantiationDeclaration = false;
7092 break;
7093 }
7094 }
7095
7096 if (IsExplicitInstantiationDeclaration)
7097 continue;
7098 }
7099
7100 // Mark all of the virtual members of this class as referenced, so
7101 // that we can build a vtable. Then, tell the AST consumer that a
7102 // vtable for this class is required.
7103 MarkVirtualMembersReferenced(Loc, Class);
7104 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7105 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7106
7107 // Optionally warn if we're emitting a weak vtable.
7108 if (Class->getLinkage() == ExternalLinkage &&
7109 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007110 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007111 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7112 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007113 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007114 VTableUses.clear();
7115
Anders Carlsson82fccd02009-12-07 08:24:59 +00007116 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007117}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007118
Rafael Espindola5b334082010-03-26 00:36:59 +00007119void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7120 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007121 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7122 e = RD->method_end(); i != e; ++i) {
7123 CXXMethodDecl *MD = *i;
7124
7125 // C++ [basic.def.odr]p2:
7126 // [...] A virtual member function is used if it is not pure. [...]
7127 if (MD->isVirtual() && !MD->isPure())
7128 MarkDeclarationReferenced(Loc, MD);
7129 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007130
7131 // Only classes that have virtual bases need a VTT.
7132 if (RD->getNumVBases() == 0)
7133 return;
7134
7135 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7136 e = RD->bases_end(); i != e; ++i) {
7137 const CXXRecordDecl *Base =
7138 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007139 if (Base->getNumVBases() == 0)
7140 continue;
7141 MarkVirtualMembersReferenced(Loc, Base);
7142 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007143}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007144
7145/// SetIvarInitializers - This routine builds initialization ASTs for the
7146/// Objective-C implementation whose ivars need be initialized.
7147void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7148 if (!getLangOptions().CPlusPlus)
7149 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007150 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007151 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7152 CollectIvarsToConstructOrDestruct(OID, ivars);
7153 if (ivars.empty())
7154 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007155 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007156 for (unsigned i = 0; i < ivars.size(); i++) {
7157 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007158 if (Field->isInvalidDecl())
7159 continue;
7160
Alexis Hunt1d792652011-01-08 20:30:50 +00007161 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007162 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7163 InitializationKind InitKind =
7164 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7165
7166 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007167 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007168 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007169 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007170 // Note, MemberInit could actually come back empty if no initialization
7171 // is required (e.g., because it would call a trivial default constructor)
7172 if (!MemberInit.get() || MemberInit.isInvalid())
7173 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007174
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007175 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007176 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7177 SourceLocation(),
7178 MemberInit.takeAs<Expr>(),
7179 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007180 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007181
7182 // Be sure that the destructor is accessible and is marked as referenced.
7183 if (const RecordType *RecordTy
7184 = Context.getBaseElementType(Field->getType())
7185 ->getAs<RecordType>()) {
7186 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007187 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007188 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7189 CheckDestructorAccess(Field->getLocation(), Destructor,
7190 PDiag(diag::err_access_dtor_ivar)
7191 << Context.getBaseElementType(Field->getType()));
7192 }
7193 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007194 }
7195 ObjCImplementation->setIvarInitializers(Context,
7196 AllToInit.data(), AllToInit.size());
7197 }
7198}